Responsive Page Layout - Reverse the Order of CSS Table Columns
September 28, 2013I’ve been working on a website redesign over the past few days, and I came across a problem with the layout. I wanted the sidebar to be to the left of the content when on a desktop, but when on a mobile device the sidebar should move to below the content. I also wanted a border between the two sections to separate them. Also the content was to use max-width: so that it would scale a little.
Here’s the HTML structure I was working with.
1
2
3
4
5
<div class="wrapper">
<div class="content"></div>
<div class="side"></div>
</div>
<div class="footer"></div>
The mobile layout would be very simple and didn’t need any styling so from here on I’m talking about the styles for the desktop media query.
The first thing I thought of was to use absolute positions, but then the footer wouldn’t stay under the wrapper, so that was no good. Then I thought there might be a way to use floats, but that would require me to place the sidebar above the content in the HML markup. After a bunch of research I couldn’t figure out how I would then place the sidebar under the content for the mobile view, so I scrapped the idea of using floats.
Time to start thinking outside of the box!
I’m a fan of the display: table
property, but I wasn’t aware of any ways to change the order of the columns, so I had held off researching this option, but its time had come. Google-ing around it was obvious not many people had this problem. I finally found a solution by a guy called Greg on StackOverflow. The solution abuses the directional property, but at the end of the day it works and the user can’t tell one way or another. Here’s my CSS to compliment my HTML structure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
.wrapper div {
padding: 10px;
}
.content {
background: #add;
}
.side {
background: #aad;
}
.footer {
width: 100%;
height: 50px;
background: #dad;
}
@media screen and (min-width: 600px) {
.wrapper {
margin: auto;
display: table;
direction: rtl;
max-width: 800px;
}
.wrapper div {
direction: ltr;
}
.content {
display: table-cell;
max-width: 600px;
background: #add;
}
.side {
display: table-cell;
width: 200px;
background: #aad;
}
.footer {
margin: auto;
max-width: 800px;
}
}
Basically what happens is that on line 19 the text direction of wrapper
is changed from left-to-right, to right-to-left, then on line 23 the divides inside of wrapper get changed back. Although this is hach-ish I’ve tested it in IE7 and it works, and I’d imagine it would work in all other browsers.
Here’s an embedded jsFiddle with the HTML, CSS, and Result. To see the columns stack and unstack just resize your browser.