![](https://img.haomeiwen.com/i3737324/6afc27e654ae5b46.jpg)
组成
如上图所示,CSS盒模型由4部分组成:
- margin(外边距)
- border(边框)
- padding(内边距)
- content(内容)
分类
CSS盒模型分为标准盒模型和IE盒模型,上图所示就是标准盒模型。
标准盒模型和IE盒模型的差别就是对宽度和高度的计算方式不一样:
- 在标准盒模型中:宽度和高度指content的高度和宽度
- 在IE盒模型中:宽度和高度值content+padding+border的和
设置标准盒模型和IE盒模型:
-
box-sizing: content-box;
(标准盒模型(默认)) -
box-sizing: border-box;
(IE盒模型)
通过JS获取盒模型的宽度和高度
dom.style.width/height
dom.getBoundingClientRect().width/height
BFC(块级格式化上下文)
原理
- 内部的Box会在垂直方向,一个接一个地放置。
- Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
- 每个元素的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如 此。
- BFC的区域不会与float box重叠。
- BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
- 计算BFC的高度时,浮动元素也参与计算
创建BFC
满足下列条件之一就可触发BFC:
- 根元素,即HTML元素
- float的值不为none
- overflow的值不为visible
- display的值为inline-block、table-cell、table-caption
- position的值为absolute或fixed
使用场景
消除垂直 margin
重叠
应用原理: BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
<section>
<style>
.wrap {
overflow: hidden;
}
p {
color: #f55;
background: #fcc;
width: 200px;
line-height: 100px;
text-align: center;
margin: 10px;
}
</style>
<article>
<p>Haha</p>
<div class="wrap">
<p>Hehe</p>
</div>
<p>Haha</p>
</article>
</section>
自适应两栏布局
应用原理: BFC的区域不会与float box重叠
<section>
<style>
.aside {
background-color: red;
float: left;
height: 100px;
width: 100px;
}
.main {
background-color: green;
height: 200px;
overflow: hidden;
}
</style>
<article class="layout">
<div class="aside"></div>
<div class="main"></div>
</article>
</section>
清除浮动
应用原理: 计算BFC的高度时,浮动元素也参与计算
<section>
<style>
.layout {
background-color: firebrick;
overflow: hidden;
}
.aside {
float: left;
}
</style>
<article class="layout">
<div class="aside">Hello World!</div>
</article>
</section>
网友评论