Consider the following HTML code:

<style>
    td {
        padding: 5px;
    }
</style>
<p>
    1233
</p>
<table>
    <tr>
        <td>
            <h3>Some text</h3>
        </td>
    </tr>
</table>

If I use <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">, the margin of <p> and <h3> does not work, but if I use <!DOCTYPE HTML>, the margin works.

What's more, when I add

h3 {
    margin: 25px 0;
}

to the style, the margin of them suddenly works even using HTML 4.0 doctype!

Why does this strange behavior happen? IE and Chrome behave the same on this issue, is this by design or something, it really confuse me.

I have a lot of pages written depend on this strange behavior, when I brought some CSS from other new components they defined margin then suddenly all these old pages broke. So I want to know what really happened.

有帮助吗?

解决方案

The issue is the suppression of default top margins in some contexts in Quirks Mode. Thus, if you use Quirks Mode for some reason (and working with legacy pages is often a very good reason), you should explicitly set any vertical margins you want to have for elements. The other solution is to move away from Quirks Mode, slapping <!doctype html> at the very start, but this may completely ruin (or maybe just disturb a little) your pages, if they have been created so that their rendering relies on buggy behavior and oddities in browsers.

The issue can be demonstrated with a simple standalone document (with no CSS):

<!doctype html>
<p>
    1233
</p>
<table border>
    <tr>
        <td>
            <h3>Some text</h3>
        </td>
    </tr>
</table>

There is empty space, about one empty line, at the beginning before “123” as well as inside the cell before “Some text”. If <!doctype html> is removed, that spacing disappears (but other margins are retained).

The issue is well described in section 10.3.10 Margin collapsing quirks in HTML5 CR: “In quirks mode, any element with default margins [such as p or h3] that is the child of a body, td, or th element and has no substantial previous siblings is expected to have a user-agent level style sheet rule that sets its 'margin-top' property to zero.”

This feature relates to the browser tradition of suppressing top margins in contexts where they are normally useless or even disturbing. For example, if a heading element or a p element is the very first element in document body, or in a table cell, there is no need to separate it from the preceding content. The practice predates general availability of CSS.

其他提示

I'm don't really know what hapening but, thats what you see in chrome at HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" is not real margins it's a some browser initial styles you can see them in chrome dev tools: -webkit-margin-before, and -webkit-margin-after; this styles ovverides by margin.

For more information you better read specs on W3C, and use doctype html, or maybe html 4.0 strict.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top