Sunday, May 31, 2009

Centering Images in CSS

The images that I have in my posts were all being aligned to the left by the Blogger platform. I thought of centering them a long time ago but modifying Blogger took a back seat to CSS. It's a very easy change that I finally got a chance to make last night and wanted to share with you.

Best way to center a block level element is to set its left and right margins to auto. The browser will compute the total available width, subtract the width of your image from the total, and divide the remaining number between the left and right margins.

Whether in Blogger, another platform or you are writing plain old CSS, if you are going to set margins in this fashion for an element, it has to be a block level element. Unlike inline elements, block level elements go all the way across their containing block. Since img is an inline element, I need to change that property to block level for the margins to work correctly.

My selector is Blogger based - the class name for the div is post-body, I add the div in front to add more specifity and write my descendant img selector:

div.post-body img {
display: block;
margin-left: auto;
margin-right: auto;
}


If you are writing this on a platform other than Blogger, you do not need the post-body selector, just use your own. If we wrote the above for the img element using a simple element type selector, it would be:

img {
display: block;
margin-left: auto;
margin-right: auto;
}


Here's the before and afters of a previous post after centering its image. Top image is left aligned, bottom is centered:

Post a Comment

Note: Only a member of this blog may post a comment.