I often find that sometimes the smallest things that were simple in regular HTML are frustratingly complex in CSS. Take, for example, centering a div. You can float it right, float it left, but there is no center. Using text-align: center does not center it either, it just makes any text inside of it centered.

It turns out it is very simple to do. The key is that you must specify a width for your div, either using an exact pixel width, a percentage, or some other measure like em units. Once you set the width, you just have to add left and right margins set to auto, and the div will be centered inside of the container it is in.

Example:

<div id="top-ad"><img src="banner.jpg">
</div>

 
To center the div, you would use the following css:

#top-ad{ width:730px; margin-left: auto; margin-right: auto;}

It turns out it was not so complex after all, just not exactly intuitive.

  • Kaimi Kyomoon

    Just the thing I was trying to figure out a few months ago. Since giving up on that I haven’t done much web design for months (or ever really). I hope I can remember this if I get inspired to try my hand at it again sometime. Thanks.

  • http://twitter.com/ethancane Ethan Cane

    Absolutely agree, not intuitive at all.