h1, h2, h3.. elements eats div margins

别等时光非礼了梦想. 提交于 2019-12-11 02:10:41

问题


Why h1, h2, h3 elements margins are ignored when in div?

http://jsfiddle.net/TzmdZ/

<div class="col">
    <h3>This is header</h3>
</div>  
<div class="col">
    <h3>This is header</h3>
</div>

.col {
    background: gray;
    margin-bottom: 1em;
}

.col h3 {
    margin-bottom: 1em;
}

When I put h element into div and there is no other text in it, though h element and div element bottom margins are spicified, h bottom margin is ignored.


回答1:


Assigning margins to two siblings will cause the margins to collapse where the margins are adjacent.

This MDN document explains the situation in detail.

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

Margin collapsing occurs in three basic cases:

  1. Adjacent Siblings
  2. Parent and first/last child
  3. Empty blocks



回答2:


Try this CSS:

.col {
    background: gray;
    padding-bottom: 1em;
}

.col h3 {
    padding-bottom: 1em;
}

Change margin-bottom to padding-bottom.

jsFiddle



来源:https://stackoverflow.com/questions/17187162/h1-h2-h3-elements-eats-div-margins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!