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>