盒模型
CSS 盒模型本质上是一个盒子,盒子包裹着HTML 元素,盒子由四个属性组成,从内到外分别是:content内容,padding内边距,border边框,margin外边距。
盒模型的分类
content-box内容盒-内容就是盒子的边界
border-box边框盒-边框才是盒子的边界
盒模型的大小公式
content-box width=内容宽度
border-box width=内容宽度+padding+margin
一般推荐使用border-box,因为当你同时设置padding,width,border的时候,border-box的大小不会变化,当你使用cotent-box时,设置这些属性,会引来非常多的问题,改到你想哭。
示意图:
如何在CSS 设置这两个模型
box-sizing: content-box;
box-sizing: border-box;
外边距合并
margin合并
可以分为兄弟margin合并和父子margin合并。
兄弟margin合并
//HTML
<div class="up">我在上面</div>
<div class="down">我在下面</div>
//CSS
.up {
width: 100px;
height: 100px;
border: 1px solid blue;
margin: 100px;
}
.down {
width: 100px;
height: 100px;
border: 1px solid red;
margin: 100px;
}
此时,两个div的实际间隔不是200px,而是100px,这就是兄弟margin合并。
父子margin合并
//HTML
<div class="parent">
<div class="child">我是儿子</div>
</div>
//CSS
.parent {
width: 100px;
height: 200px;
background: red;
margin-top: 50px;
}
.child {
width: 50px;
height: 50px;
margin-top: 100px;
border: 1px solid blue;
}
这时,父元素展示出来的外边距将是子元素margin-top与父元素margin-top中的较大值,也就是儿子中的100px
BFC
一个**块格式化上下文(block formatting context)**是Web页面的可视化CSS渲染的一部分。它是块盒子的布局发生,浮动互相交互的区域。
通俗的讲,可以将BFC理解为一个封闭的大箱子,不论里面的元素如何变化,都不会受到影响。
BFC的触发条件
- 浮动元素(元素的 float 不是 none)
- 绝对定位元素(元素的 position 为 absolute 或 fixed)
- 行内块元素
- overflow 值不为 visible 的块元素
- 弹性元素(display为 flex 或 inline-flex元素的直接子元素)
BFC的用途
- 清除浮动
- 解决外边距合并
- 布局
上面例子的解决方案
将两个外边距重合的元素放在不同的BFC容器中
兄弟margin合并
//HTML
<div class="up">我在上面</div>
<div class="down">我在下面</div>
//CSS
.up {
width: 100px;
height: 100px;
border: 1px solid blue;
margin: 100px;
}
.down {
width: 100px;
height: 100px;
border: 1px solid red;
margin: 100px;
display: inline-block; // 触发BFC
}
父子margin合并
//HTML
<div class="parent">
<div class="child">我是儿子</div>
</div>
//CSS
.parent {
width: 100px;
height: 200px;
background: red;
margin-top: 50px;
overflow: hidden; // 触发父元素FBFC,取消上边距合并
}
.child {
width: 50px;
height: 50px;
margin-top: 100px;
border: 1px solid blue;
}
总结
对于两种盒模型,使用border-box是更好的原则。当发生margin合并的时候,不要慌张,使用BFC解决合并问题。