This is something that's just pissed me off for a long time, and has been one of those "Fuckit, I'll just use a table here" to get a block of "stuff" centered on a page or within another div. Think about it: text-align doesn't work (unless of course the content of the div is nothing but text) and you can't margin: 0 auto; unless the div you're centering has a fixed width. The reason for this effort, of course, is that tables are just a no-no when it comes to white hat SEOing your pages.
So I saw this done, tried it and it works like a charm. (BTW - I am writing it this way because I am sureasshit to forget this technique in 20 minutes. This is actually for me)
- the only thing that will make the size of a div compress up to the size of the inner content is float.
- if you position: relative things, then float: left takes on a completely different meaning.
- You are allowed to negatively "left" items if they are position-relative.
With those rules in force, consider this little piece of HTML and then I will explain it.
<div style="float: left; position: relative; left: 50%; background-color: yellow;">
<div style="float: left; position: relative; left: -50%; background-color: blue;">
Here is some text
Here it is: the inner content is positioned side by side. That makes the the two containing divs exactly the total outside size of the inner content - because they both are floated left. The outside div is positioned so that it's leftmost corner will be at exactly 50% of it's container - be that another div or the body or whatever. Remember that the inner div will be exactly the same size as the outer div: so at -50% left, it will be 50% of the size of it's containing div - in other words, the outer div is used to find dead center, the inner div then moves left 50% of it's own size. I put the background colors in there so that you could see what's going on if you use the above code as an example.
WHAT A CHARLIE FOXTROT. But it works. If you need to have content that is larger than the viewable window, then you might want to put the whole mess in another div with overflow: hidden so that you don't get a scroll bar at the bottom. It'll still all work correctly, but you'll have an invisible reason for a big ol' scroll bar at the bottom.