In this Weekly Web Hack, I'll demonstrate how to have semantically ordered HTML elements appear visually reordered static width, center floated, single column page.
By the end of this article, you should be able to:
For those of you who just can't wait to see a working example:
Here are the requirements for the project:
First, let's lay out the HTML elements as we'd like them to appear. Consider this HTML snippet:
<body>
<div id="globalWrapper">
<div id="firstBox"> The First Box! </div>
<div id="secondBox"> The Second Box! </div>
</div>
</body>
In this case, the globalWrapper represents our single column, and firstBox and secondBox contain our semantically ordered content. The first div contains the relevant page content, while the second div would contain a header of some sort - generally something we'd like to visually display on top of the "first" box.
First, here is the CSS for the globalWrapper:
#globalWrapper { width: 500px; margin: 4em auto 0 auto; }
This relatively terse code establishes the following about the globalWrapper:
The top margin of 4em is important since this must be tall enough to accommodate the secondBox. Ideally the second box would have a static height - which is usually the case for header bars.
Next, here's the CSS for the firstBox:
#firstBox { color: white; background: red; width: 500px; padding: 1em; }
Here we're redefining the 500 pixel width again. This is to account for the 1em padding, which could otherwise muck with the browser's width calculation. If the padding would instead be set to 0, the width attribute could be safely removed.
Finally, this is the CSS for the secondBox:
#secondBox { color: white; background: blue; width: 500px; padding: 1em; position: absolute; top: 0; left: auto; z-index: 0; }
In this case, we start off with almost exactly the styles for firstBox. However, unlike the other divs in the example which will be placed relative to their parent elements, this box has a position attribute of 'absolute'. The "top:0;" declaration means the div should be placed 0 pixels down from the top of the page, which will put it into globalWrapper's top buffer (or "gutter" as they're sometimes called).
The magic glue that holds this hack together is the "left: auto;" declaration. This tells the browser that the left-hand margin should be calculated in such a way that the div will be positioned in the center of the page.
The above has been put together and is available for inspection here: absolutely-relative.html
I have tested this locally on Firefox, Opera and Konqueror. Using Geotek's netrenderer produces good results for IE 6 and 7.
Of course, as with many hacks, this one needs some use-case specific TLC from any developer that chooses to use it. What follows are a few things to think about during implementation.
Anyway, I sincerely hope this helps someone out there. Enjoy! As always I'll be happy to answer any questions.
Got something to say?
or, read what others have said...