Reordering columns

A basic technique for swapping two columns in a layout.

In the following example, a content area follows a sidebar in document order:

<div id="example1">
    <div class="sidebar"></div>
    <div class="content"></div>
</div>
.sidebar, .content { height: 60px; float: left; }
.sidebar           { width: 100px; background-color: #9DB029; }
.content           { width: 300px; background-color: #3465A4; }

Sometimes, there exists a need to swap the two around, without modifying their order in the original document. To achieve this, we can use negative margins:

#example2 .sidebar { margin-left: 300px; }
#example2 .content { margin-left: -400px; }

Just to clarify those measurements:

  1. First of all, to shift the sidebar to the right, we need to give it enough of a margin to accommodate the content box. Since that box is 300px in total width, a left margin of the same amount gives that space
  2. Then, we need to shift the content in the opposite direction, via a negative margin. Since the content comes after the sidebar in the DOM, shifting the sidebar also shifts the content, so we need to move it back by the total size of the shift (300px) plus the width of the sidebar (100px), hence the value of -400px.

References


Tweet

Comments

Leave a comment