Alternative to Using Tables for Layout

Most developers are familiar with tables and how they behave. They have relied on them heavily in the past to display data as well as templating and design. But as we learned in my previous post you are no longer encouraged to use them for layouts. You should use CSS instead.

When I first started dabbling with DIV tables I used the CSS float property to mimic cells. But in many situations that method forced me to be overly specific on the heights and widths of my cells. It seemed to be two-times the work. Also vertical alignment and centering was much more difficult.

But luckily CSS3 has a solution for us with the DISPLAY property: table, table-row and table-cell.

In the following example I have some HTML:
And when you include a little CSS:
Above, I am showing how to easily center a table with auto-sized columns and rows based on the content. I’m also vertically and horizontally aligning a cell with ease. Heights and widths were not required. The height that was set was only to demonstrate vertical-alignment.

The CSS display properties work in all major browsers. They became fully functional as of IE9 but can work in IE8 with an additional meta tag. See this post for more information. IE8 was released on March 19, 2009 and IE9 on March 14, 2011.

Remember that it is just as bad to use tables for layout as it is place tabular data into a DIV table. Tables still have a purpose! If you are confused on when to use each then you may find a better understanding in my previous post.

See a DEMO.