css - div下的h1 bootstrap设定的margin-top失效了?

查看:191
本文介绍了css - div下的h1 bootstrap设定的margin-top失效了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在用bootstrap3做项目时,发现被bootstrap3设定的h1的margin-top:20px;失效了,如下:

https://jsfiddle.net/DTcHh/30...

HTML

<div class="header">
  <h1>123</h1>
</div>

CSS

div.header{
 
  background-color:blue;
}
h1{
  background-color:red;
}

参考了w3cschool card的范例(https://www.w3schools.com/w3c...后,发现他在div.header上加了个:after和:before,内容是:
https://jsfiddle.net/DTcHh/30...

.header:after,.header:before{
    content: "";
    display: table;
    clear: both;
}

请问在:after,:before这三行是什麽巫术这麽神奇,为什麽会这麽使用呢?

解决方案

首先回答第一个问题,margin-top失效了,原因是发生了margin collapse。
先来看规范中的描述,

The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.
它提到了父元素必须没有top border,top padding, 并且这个子元素必须没有clear属性。

那么我们尝试一下设置top border | top padding 。
top border
top padding
此时你可以很明显的看到margin神奇的重新出现了。

接下来, 我们解释为什么添加了before, after属性以后就可以了。
before,after都是伪元素,我们可以把它们看做真正的元素,那么它们就是div的子元素了,然而这个块级子元素拥有着一个clear属性导致其无法和其父元素发生margin collapse,
再来看这句,

The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.

所以这个before元素也无法和h1发生折叠,同样是因为设置了clear属性,

The bottom margin of an in-flow block box with a 'height' of 'auto' and a 'min-height' of zero collapses with its last in-flow block-level child's bottom margin if the box has no bottom padding and no bottom border and the child's bottom margin does not collapse with a top margin that has clearance.

我觉得设置after是为了阻止div中最后一个子元素的bottom margin和父元素 div 的bottom margin发生折叠。

仅作参考,

这篇关于css - div下的h1 bootstrap设定的margin-top失效了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆