Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

html - Why doesn't a <table>'s margin collapse with an adjacent <p>?

From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here:

table {
  margin: 100px;
  border: solid red 2px;
}
p {
  margin: 100px
}
<table>
  <tr>
    <td>
      This is a one-celled table with 100px margin all around.
    </td>
  </tr>
</table>

<p>This is a paragraph with 100px margin all around.</p>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Margin collapsing is only defined for block elements. Try it - add display: block to the table styles, and suddenly it works (and alters the display of the table...)

Tables are special. In the CSS specs, they're not quite block elements - special rules apply to size and position, both of their children (obviously), and of the table element itself.

Relevant specs:

http://www.w3.org/TR/CSS21/box.html#collapsing-margins
http://www.w3.org/TR/CSS21/visuren.html#block-box


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...