Search code examples
csshtmlposition

Position div box at the end of after ensuing elements


If I have 3 Div boxes (any number really) ordered in the following manor:

<div>
    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
</div>

How can I make the div with id one be displayed after the div with id three without changing the structure of the html?

This is what the html should be displayed as:

________________________
| ____________________ |
| | id=two           | |
| |                  | |
| |__________________| |
| ____________________ |
| | id=three         | |
| |                  | |
| |__________________| |
| ____________________ |
| | id=one           | |
| |                  | |
| |__________________| |
|______________________|

Solution

  • It's possible depending on what comes after those divs. If there's nothing there, you can use position: absolute; top: 100%; on the first div to achieve that:

    <div id="container">
        <div id="one"></div>
        <div id="two"></div>
        <div id="three"></div>
    </div>​​​
    
    ​#container { position: relative; border: 1px solid red; }
    #one { position: absolute; top: 100%; }
    #one, #two, #three { width: 300px; height: 200px; border: 1px solid #ccc; }
    

    http://jsfiddle.net/xjnrE/

    However, if there's anything after the #container div, it will be under #one (at least partially, depending on the height; see demo).

    Keep in mind that if the element is "in the flow" (i.e., it's not positioned and not floated), it will be rendered according to the order of appearance on the markup (and, consequently, the DOM). This means you must resort to JavaScript to change the actual position of the element in the DOM:

    var container = document.getElementById('container');
    var one = document.getElementById('one');
    container.appendChild(one);
    

    http://jsfiddle.net/xjnrE/3/