Alkaline Alkaline - 4 months ago 9
HTML Question

Transposing div elements using CSS

I'll jump to an example.

<!DOCTYPE html>
<head>
<title>Transposing div using CSS</title>

<style>
div#wrapper {
}

div#menu {
border:blue solid 1px;
}

div#main {
border:red solid 1px;
}
</style>
</head>

<body>
<p>How do we show the menu div immediately after the content div?</p>
<div id="wrapper">
<div id="menu">Menu</div>
<div id="main">Content</div>
</div>
</body>
</html>


In a browser, the menu div will come first in the flow. Now let's say that I need to change the layout so that "Menu" follows the content div content. How can this be done using CSS only. That means no change to HTML (no user agent detection stuff) and no JavaScript code.

The main CSS technique to position elements is to use the float:right|left attribute. It works well to move elements with respect to their bounding box, but I'm looking at moving an element at the end of its successor element in the normal flow.

And here's the use case. I want a web site to show up optimally on small screen browsers like on an iPhone. The web site currently has the menu at the top and content below, a very common layout but on an iPhone, the real estate is so limited that it would be preferable to have the menu following the main text content.

The solution only has to work with iPhone and Android mobiles (WebKit-based). So no need for taking into account Internet Explorer hacks and such.

Answer

If your menu has a fixed height (which most likely it does) you could use the same principles as the sticky footer: apply position relative on the wrapper, and a bottom padding of the same height as the menu. In code:

div#wrapper {
    height: 100%;
    padding-bottom: 100px;
    position: relative;
}

div#menu {
    border:blue solid 1px;
    position: absolute;
    bottom: -2px; /*to offset the border pxs*/
    height: 100px;
    width: 100%;  
}

div#main {
    border:red solid 1px;
}

You can view it in action here: http://jsfiddle.net/3ZheQ/