Reordering of Divs

There is no catch-all way of reordering elements with css.

You can inverse their order horizontally by floating them all to the right. Or you can position them absolutely relative to the body or some other containing element - but that comes with severe limitations regarding the size of the elements, and positioning relative to other elements on the page.

Short answer: You can only achieve this in a very limited set of circumstances. Reordering elements is best done in markup.

If you have no control over the html, you could use javascript. Here using jQuery:

$("#div2").insertAfter("#div3");
$("#div1").prependTo("#div2");

I certainly don't recommend that unless your hands are tied. It will be harder to maintain, and for your end users it will make your page "jerk around" while its setting up the page.


I would use Javascript to traverse the nodes accordingly. If you want to use a library like jQuery, you can use the above suggestions. If you'd prefer not to have the bloat, use the following simple and minimalistic solution...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Test</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
      function swapSibling(node1, node2) {
        node1.parentNode.replaceChild(node1, node2);
        node1.parentNode.insertBefore(node2, node1); 
      }

      window.onload = function() {
        swapSibling(document.getElementById('div1'), document.getElementById('div2'));
      }
    </script>
  </head>
  <body>
    <div id="div1">1</div>
    <div id="div2">2</div>
    <div id="div3">3</div>
  </body>
</html>

Best regards...

EDIT: Changed function name from swapNode to swapSibling, as I am fairly certain this will only work with nodes that have the same parent.


Since now flexbox is widely supported you can also use it to reorder divs using only css:

<div id="container">
    <div id="div1">1</div>  
    <div id="div2">2</div>  
    <div id="div3">3</div>
</div>

And css:

#container{
  display: flex;
  flex-direction: column;
}

#div2{
  order:2
}

#div3{
  order:1
}

It would display:

1
3
2

You can try it on this fiddle.