盒模型 与 BFC
盒模型包含
content
padding
border
margin
IE模型
IE5.5以及更早的IE浏览器使用的盒模型
width
和height
包含了content
、padding
、border
css设置:
box-sizing: border-box;
标准模型
现代浏览器默认使用标准模型
width
和height
只包含content
css设置:
box-sizing: conent-box;
JS如何设置获取盒子模型对应的宽和高
dom.style.width = '888px'; // 设置
window.getComputedStyle(dom).width; // 获取 标准模型下的宽度,不包含 padding和border
dom.getBoundingClientRect().width; // 受 box-sizing 设置影响,box-sizing: border-box时,包含 padding和border
BFC(块级格式化上下文)
Block Formatting Contexts
一个隔离了外界的独立容器,容器里面的元素不会在布局上影响到外面的元素
BFC
具有普通容器所没有的一些特性:- 同一个
BFC
下外边距会发生折叠 => 不同BFC可以避免外边距折叠margin-collapse
BFC
可以包含浮动的元素BFC
可以阻止元素被浮动元素覆盖
- 同一个
触发BFC的条件:
html
根元素- 浮动元素:
float
除none
以外的值 - 绝对定位元素:
position
(absolute
、fixed
) display
为inline-block
、table-cells
、flex
...overflow
除了visible
以外的值 (hidden
、auto
、scroll
)
应用: 清除浮动
1. 清除浮动的办法
- 浮动元素的兄弟节点,添加
clear:both
- 父元素的
:after
伪类,添加clear:both
,zoom: 1
(IE转有属性)可解决ie6,ie7浮动问题 - 父元素添加
overflow: hidden
- 父元素添加
display: table
- ...
2.手写 clearfix
.clearfix:after {
content: '';
display: block;
clear: both;
}