Horizontally centering text or images should be an extremely easy task in the XHTML/CSS world. I remember the good old day when you wanted something centered, you would just wrap the thing you wanted centered with the <center> tag and all was dandy. Your job was done.

However, there is one small problem with the center tag: It is not semantically correct. Say you have a design where a picture and some text was centered. Then, a year down the road, you have a redesign and all of a sudden it makes no sense to center that picture with the new positioning of elements. That means you’d have to find all pages where that center tag existed and delete them out. CSS is here to take care of that. CSS is about smaller download size, better standards compliance and a central style that can be changed in an instant.

So, to horizontally center an item, I always pull the following CSS trickery:

<div id="container">
<img src="..." alt="My Image" />
</div>

To center the image in standards-compliant browsers, you’d have to create the following CSS rules:

div#container img{
margin:0px auto 0px auto;
}

As you can see, the right and left margins are set to auto, which tells standards-compliant browsers to create the margins for left and right of the image automatically, which centers the image.

However, this little trick doesn’t quite work in Internet Explorer, so we need to create the following CSS rule to make IE behave:

div#container img{
margin:0px auto 0px auto;
}
div#container{
text-align:center;
}

The text-align:center; rule outside of the image makes all content center (including text), hence the image will center.

Check back soon for the third CSS trickery article.

Comments

6 Comments

  1. Sam said 2535 days ago

    Sams CSS Trickery Shortcuts 101:

    div#container img{
    margin: 0 auto;
    }

    Essentially does the exact same thing, just with less code.

  2. rogie said 2535 days ago

    Nice one Sam! Thanks for the CSS Hotness.

  3. Jeff said 2531 days ago

    Naughty, Sam. You need to append the 0 with a px, em, %, etc for full CSS hotness. Rock on!

  4. Arnor said 2504 days ago

    Jeff: 0 = nothing, so it doesn’t even make sense to add px, em or % to it… In fact, the W3C reccomends you don’t…

    Again, CSS is about minimal download quantities… And the bare ‘0′ without ‘px’ is two charcters less to download…

  5. ikram_zidane said 2446 days ago

    i think with text-align:center.. its already enough to cenetr the image.. cuz its in div..

  6. rakesh said 2421 days ago

    the text-align:center will do the trick no need for the margin property.

Sorry, the comment form is closed at this time.