Posts Tagged ‘IE6’


30

May

Center a table with CSS

POSTED May 30th, 2008 by Micah in Web Design | No Comments »

Generally, we don’t much like table-based layouts around these parts. As I like to put it, tables are for boring data, not beautiful design. Sometimes however, working to make a quick change to a site designed elsewhere can require a comprimise.

In this case, I’m referring to a table layout I inherited that I wanted to make centered in the browser window, and only by changing the CSS (and without adding a new id on every single page) Here’s how I did it:

First I tried the idealistic (proper) method, fingers crossed:

body > table {
	margin: 0 auto;
}

It worked… almost. It worked on the usual suspects – Safari 3, FireFox 2 Mac/PC, IE 7. But of course, IE 6 doesn’t recognize child selectors.

Next, I tried a less pretty but ultimately effective method that utilizes the C in CSS… “Cascading.” That’s right, it can be used to your advantage! For this method I made two definitions in my CSS:

First, I styled every table within the body tag:

body table {
margin: 0 auto;
}

Then, I reset the margins of any tables nested within the first table.

body table table {
	margin: 0;
}

And that worked on all mentioned browsers, and it’s pretty much just long hand for the child selector version I tried first. Outside of looking a little like myspace code, I can live with it. After all, we’re talking about a table layout! Dirty CSS is the least of its problems.

Tags: , ,