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 | |
| | | |
| |__________________| |
|______________________|
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/
If you control the dimensions of the divs and are sure that their contents will not break your layout,you could position them with css. A bit awkward, but something like:
#one, #two, #three {
position: absolute;
width: 200px;
height: 200px;
}
#one {
top: 400px;
}
#two {
top: 0px;
}
#three {
top: 200px;
}
These positions could then be changed with javascript if you need to.
The following grab the first DIV and move it to be the last item in the parent container.
However, you will need to make sure you can target the container DIV somehow. So if you cannot edit the HTML, target the element based on some other parent element with a unique ID or class.
Markup:
<div id="container">
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</div>
JavaScript:
$('#container #one').appendTo('#container');
FTR: flexbox
support has matured since then, offering a clean solution.
/* That's all: */
#container { display: flex; flex-direction: column; /* omit the latter for horiz. stacking */ }
#one { order: 99999; /* Alas, no "last"... */ }
/* Demo visuals only: */
#one { background: pink; }
#container > div { width: 100px; height: 100px; border: 1px solid grey; }
<div id="container">
<div id="one"> FIRST </div>
<div id="two"> second </div>
<div id="three"> third </div>
</div>