Saturday, November 17, 2007

Putting DIV inside of DL breaks Internet Explorer DOM

While writing a page that extensively uses definition lists (dl), I came across a pretty bad problem with Internet Explorer (6 and 7). Each dl must be completely contained in one div, you cannot put a div inside of the dl. If you do, all of the style information from all DIV's above the DL will be lost when you close the DL. Here's an example:
<div style="font-weight: bold;">
<dl>
<dt>Term 1</dt>
<dd>Definition 1</dd>
<div style="text-align: center;">
<dt>Term 2</dt>
<dd>Deinition 2</dd>
</div>
<dt>Term 3</dt>
<dd>Definition 3</dd>
</dl>
</div>

This page will render fine in Firefox - 1 and 3 are bold but not centered, and 2 is bold and centered. Things are different in IE however. 1 is bold and not centered (correct). 2 is bold but not centered (incorrect) even though the div explicitly sets centering, and 3 is not bold (incorrect), even though it is within the DIV tag specifying bold. To get DIVs and DLs to work correctly in IE, you cannot put a DIV inside of a DL. You must make a separate definition list for every div element. Here is the above example changed to work in IE:

<div style="font-weight: bold;">
<dl>
<dt>Term 1</dt>
<dd>Definition 1</dd>
</dl>
<div style="text-align: center;">
<dl>
<dt>Term 2</dd>
<dd>Deinition 2</dd>
</dl>
</div>
<dl>
<dt>Term 3</dt>
<dd>Definition 3</dd>
</dl>
</div>

This isn't that much of a pain to do, it just took some hair pulling on my part to figure out why things were all messed up in IE. If you know of a different way to do this, or know why IE behaves this way, please post a comment.

2 comments:

Anonymous said...

Have you run each of those through W3C's validator? Is a div tag inside a definition list valid HTML?

Brent said...

I just did run this through the W3C validator, and it is not completely valid, the div is not allowed inside of a dl. I guess that's why IE doesn't render it correctly.