November 23, 2011
Vertically Center an Image with CSS - A New Method
Vertical centering with CSS is hard. It's hard in general, and it's hard when you need to vertically center an image, which is what I needed to do today.
There are many methods for this, most of which are limited to cases in which you know the height of the image to be centered. Other methods work for images of unknown height but fail in IE6/7. Fortunately there's at least one method that covers both bases; however it requires three wrapper divs on the image, which is kind of like wearing three winter coats at once. (See Vertical Centering in CSS and scroll down to "Let's make it structural and without hacks.")
Today I came up with a different approach, one in which the image is loaded via inline CSS.
Here's the markup and CSS (in this example, I'm also horizontally centering the image):
<div class="vertically-center" style="background-image: url(/media/img-walt.gif)"></div>
.vertically-center {
background-position: 50% 50%;
background-repeat: no-repeat;
height: 200px;
width: 200px;
}
An example image, vertically and horizontally centered in a 200px by 200px div:
Suffice it to say, the method is not ideal. For one thing, no alt text. For another, limited use cases. However, such use cases do arise, as one did for me today, and when it does, I plan to use it.
Published in CSS
What Is This?
This is a blog about better websites—how they're made and what makes them better. Think of it as Apocalypse Now but with the word Apocalypse changed to Quality and the theme shifted from madness to best practices in web development. It's written by me, Michael Barrish.
Song of My Professional Self
I celebrate myself, and sing myself. I build bulletproof websites using web standards and related best practices. I work with designers and companies needing expert style and markup. Clear and sweet is my soul→
Weblog Articles
Latest
- Vertically Center an Image with CSS - A New Method
- Today I came up with a different approach, one in which the image is loaded via inline CSS.
- Death of a Standardista
- I have no interest in building kick-ass containers for crappy content.
- Great Copywriting—Not for Robots
- Neither for the faint of heart nor the narrow of mind.
- The Death of TimesSelect and the Future of Web Advertising
- There's a lesson in this, and it's not that information wants to be free.
Popular
- Adblock Plus Must Die
- An anarchist superhero comes from the future to rid humans of ads forever.
- Clients and Copy
- When the copy sucks, the website sucks.
- Pipe Dream
- I just solved a longstanding CSS problem: pipe lists.
- Confessions of a Bad Designer
- I'm a one-trick pony, and my trick doesn't necessarily work.