Monday, January 19, 2009

HTML/CSS: Table inside table getting out containing cell with IE

Consider this table with a width: 100% displayed inside a table cell:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<table style="width:100%; border: 1px solid red">
<tr>
<td>
<div style="padding-left: 3em;
padding-right: 3em">
<table style="width: 100%;
border: 1px solid blue">
<tr>
<td>Gaga</td>
</tr>
</table>
</div>
</td>
</tr>
</table>

</body>
</html>

With IE, the table "gets out" of its containing cell. Notice that it is as if the width of the inner table was calculated without taking the padding into account, but its position inside the cell was taking the padding into account:
HTML_CSS_ Table inside table getting out containing cell with IE - Google Docs.png
The expected result is rather:
ff-ok-1.png
There are two ways to fix this:

The clean way – Switch the rendering from quirks mode to strict mode by changing the doctype. If you can, I'd recommend you do this. This means that in the above code, you would just replace the doctype declaration with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

The workaround way – Instead of defining the padding on a div, you put it directly on the outer cell, and remove the div, which gives you the following code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<table style="width:100%; border: 1px solid red">
<tr>
<td style="padding-left: 3em; padding-right: 3em">
<table style="width: 100%;
border: 1px solid blue">
<tr>
<td>Gaga</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

2 comments:

Fabão said...

Hello from Brazil
Thanks for this post. It helped me a lot.
I was trying to fix a problem like this. I have a main table just to center the page in the browser, and a few other tables inside the main one. It was funny: the page looked fine in Firefox, Netscape and Safari browsers, but one of the tables just didn't appear in IE nor in Opera browsers.
I realized that when I changed the width property other than 100% (or x%) the table was shown, but different from what I wanted.
Your "padding" tip solved my problem.
tks

Alessandro Vernet said...

Fabão, I am glad this helped! Thanks for letting me know.