基本概念
标准盒模型+IE盒模型
标准盒模型 和 IE盒模型的区别
标准盒模型:margin(外边距) + border(边框) + padding(内边距) + content(内容);width指的是内容区域content的宽度;height指的是内容区域content的高度。
IE盒模型: width + margin; width指的是内容、边框、内边距总的宽度(content + border + padding);height指的是内容、边框、内边距总的高度
css设置两种盒模型
box-sizing: content-box; // 标准盒模型 浏览器默认
box-sizing: border-box; // IE盒模型
js如何获取对应盒模型的宽高
通过DOM元素的style属性,取内联样式的宽高
dom.style.width/height
浏览器渲染后的宽高
dom.currentSyle.width/height //只有IE支持
window.getComputedStyle(dom).width/height // 兼容性更好
dom.getBoundingClientRect().width/height
实例:根据盒模型解释边距重叠
BFC(边距重叠解决方案)
BFC基本概念:块级格式化上下文
BFC原理:
- BFC这个元素的垂直方向的边距发生重叠
- BFC的区域不会与浮动元素的box重叠,清除浮动
- BFC在 页面中的一个独立的容器,容器里面的子元素不在布局上影响到外面的元素。
- 计算BFC高度,浮动元素参与计算
产生BFC:
- 根元素
- float不为none
- position不为static或relative
- overflow不为visibility
- display为inline-block,table-cell
BFC使用场景:
解决BFC垂直方向边距重叠:
解决方案: 给子元素增加一个父元素,父元素创建一个BFC
<style>
html * {
margin: 0;
padding: 0;
}
.box {
overflow: hidden;
background: green;
}
.box p{
margin: 10px auto 20px;
background: red;
}
</style>
<div class="box">
<p>1</p>
<div style="overflow: hidden;">
<p>2</p>
</div>
<p>3</p>
</div>
布局时BFC应用,使用浮动,一侧固定,一侧自适应,自适应内容超出时,占用 固定部分的位置
解决方案: 给自适应元素创建BFC
.layout {
background: red;
}
.layout .left {
width: 100px;
height: 100px;
background: hotpink;
float: left;
}
.layout .right {
height: 110px;
background: #eee;
overflow: auto;
}
<div class="layout">
<div class="left"></div>
<div class="right"></div>
</div>
清除浮动:创建BFC,计算高度,浮动元素参与计算
BFC子元素即使是float也会参与高度计算
.float {
background: red;
overflow: hidden;
/* float: left; */
}
.float .child {
float: left;
font-size: 30px;
}
<div class="float">
<div class="child">
浮动元素
</div>
</div>