Responsive two-column layout using table display

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In a previous tutorial, we learned how to make a responsive two-column layout using “box-sizing: border-box” to put in the padding between the columns.   In this tutorial, we will also make a responsive two-column layout.  But we will using the table display technique.

Let’s start with this mobile friendly HTML code (more about this in tutorial here)…

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Responsive Two Column Layout using negative margin</title>
    <style>
    </style>
  </head>
  <body>
     <div id="pagewrapper">
     </div>
  </body>
</html>

And with this CSS…

#pagewrapper {
    border: 1px solid #999;
    background-color: #f5f5f5;
    margin: 10px 50px;
}

So far this only gives us a blank page.  We need add two divs of class “column-half” to represent our two columns.  And add a div of class=”row” to contain the two columns…

html for the two columns

html for the two columns

And when we view it in the browser, we get the two columns one on top of another …

two columns one on top of another

two columns one on top of another

This is the mobile view.  What users would see if they were looking at the page on mobile devise.  If they were looking on a desktop browser with width greater than 500px, we will make the two columns side-by-side by adding these CSS code within a media query …

table layout css

table layout css

We see this rendered in our browser with the two columns side-by-side almost as if the two columns are in table cells of a table…

columns as in table cells

columns as in table cells

This is because we told the row to behave like a table of width 100% (using “display: table”).  And we told the columns to behave like table cells of width 50% (using “display: table-cell”).  Table-cells by nature goes side by side.   The “table-layout: fixed” is not really needed in this case because a width on the cells are specified.  But the “fixed” value means that the cell width depends only on the width of the column and width of the table, and not on the content of the cell.  The default value of “auto” will tell the browser to determine the width of cells based on cell content (if width of cells is not explicitly specified).

To add padding between the columns, we add …

add padding on columns

add padding on columns

and get …

two column table layout

two column table layout

Because the table code is within a media query that is only applied when width greater than 500px, the two columns still drops to one on top of another in mobile view. So it is a responsive layout.

You can see the full code in action here.