Nov 26

Fake Table Columns Using CSS

Anyone who's been doing the HTML side of web design for a while has most likely laid out a page using tables. Nowadays, that's frowned upon…and for good reason. But sometimes, tables are just handy! Sometimes it's difficult to do what tables can do without them. But since I'm committed to using semantic HTML as much as possible, I'm always experimenting to figure out new ways to simulate tables' behavior.

I've had some limited success in simulating tables, in limited circumstances. This is one of those circumstances. In this instance, I was wanting two columns of content (not columns for page layout, that is). The exact behavior I was wanting is to give the left column a fixed width and have the right column be as wide as necessary to fill the remaining space, as seen in figure 1.

figure 1: illustration of one fixed width column and one variable width column
figure 1

I also wanted the left column to resize if the text on the page was resized, to allow for flexibility in browser settings, and the solution turned out to be relatively simple. Simply float the left element and give it a width in ems. Then make sure the right element has “display: block;” and give it a left margin equal to the width of the left element (using ems). See figure 2 for an example. Voila! Problem solved!

figure 2: CSS for one fixed width column and one variable width column. Left column, float left, width ten ems. Right column, display block, margin left ten ems.
figure 2

I enjoy using this trick with forms. If you treat the input labels as the left elements and also give them “text-align: right;” then group the input and any other items  next to it together in an element on the right, you get a marvelously center-aligned form! (Make sure to give all the labels a width in ems that's large enough to accommodate the longest label.)