Centering Variable Width Content

Say you have some content with variable width. If it is just text, you can probably get away with text-align:center. But say it is an image, and that image may have different dimensions. How do you consistently center it on the page?

First, put the content inside a floated div, because floated divs will shrink wrap around the content. Second, wrap that div in another floated div.

Now here's the good part. Relatively position the outer float (yellow) left:50%, so that the left edge is at the middle of the page. Then relatively position the inner float (red) left:-50% to shift it exactly 1/2 of the yellow div's width to the left, so that it is centered. Note that the yellow div and the red div are exactly the same width, because the yellow is also a float, so it is shrink wrapped to fit around the red one.

The background colors and heights are included to make it clear what is happening. Normally, the yellow div would have no height spec and no padding, and would be set to your background color. The red div is the one that we are trying to center.

 

This is a div with an unknown width

Some slightly wierd stuff happens if the div being centered is really wide, because the right edge of the yellow div will extend beyond the right of the page.

This is a div with an much wider width, to make the yellow div go off the page to the right. We'll type a bit more to be sure.

Most people will see a horizontal scroll bar on the bottom, unless their screen is very wide.


The fix for the horizontal overflow is to nest everything within another container (aqua), with overflow:hidden;. The aqua div will always fill 100% of the page width, and will cut off any part of the yellow div that tries to escape!

This is a div with an much wider width, to make the yellow div go off the page to the right. We'll type a bit more to be sure.

Most people will see a horizontal scroll bar on the bottom, unless their screen is very wide.

Thanks to Matthew James Taylor, who's page taught me how to do this. http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support