1.盒子塌陷的原因
在构建页面的时候需要使用到一些盒子模型来完成我们对页面的排版,并且盒子套盒子的情况也是非常常见的,正常情况下如果父盒子没有设置高度,子盒子会撑开父盒子使父盒子达到子盒子的高度,但是如果子盒子使用了浮动,子盒子就会脱离了文档流,引起盒子塌陷,绝对定位和固定定位也会引起盒子塌陷。
首先,设置一个父div和一个子div,其中父盒子不设置高度,子盒子高宽都设置
html:
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
</html>
css:
*{
margin: 0px;
padding: 0px;
}
.one{
width: 300px;
margin-left: 50px;
background-color: aquamarine;
}
.two{
width: 100px;
height: 100px;
background-color: rgb(210, 70, 70);
}
正常情况下结果:父盒子没有设置高度,它的高度就是子盒子的高度
1.给子盒子设置浮动,结果就只有子盒子存在,父盒子由于没有元素支撑没有显示
.two{
width: 100px;
height: 100px;
float: left;
background-color: rgb(210, 70, 70);
}
2.给子盒子加上绝对定位,一样会导致盒子塌陷,为什么呢?
因为绝对定位也是脱离文档流,绝对定位是相对于存在定位属性的父元素进行偏移,父元素无定位则顺推至祖先元素判断是否存在定位,若存在则相对于祖先元素进行偏移,若不存在则以此类推直至无祖先元素,若无父元素,则相对于浏览器进行偏移,由于父元素本身没有高度而不会有空间存在,所以就会相对于浏览器偏移,进而导致盒子塌陷。
.two{
width: 100px;
height: 100px;
position: absolute;
/* float: left; */
background-color: rgb(210, 70, 70);
}
3.给盒子加上固定定位,结果也是如此,为什么呢?
因为固定定位也是脱离文档流,是相对于浏览器窗口进行偏移,定位参照点跟父元素没有关系。
2.如何清除盒子塌陷呢?
1.给每个盒子的宽高都写死,大小合适为止
- 优点:简单方便
- 缺点:非自适应,浏览器的窗口大小直接影响用户体验。
2.给父盒子也添加浮动,让其也脱离标准文档流。
- 优点:方便;
- 缺点:对页面的布局不是很友好,不易维护。
.one{
width: 300px;
margin-left: 50px;
float: left;
background-color: aquamarine;
}
.two{
width: 100px;
height: 100px;
float: left;
background-color: rgb(210, 70, 70);
}
3. 给父盒子添加overflow:auto;
或者overflow:hidden;
。
使用overflow: hidden
时,实际上就创建了一个块级格式化上下文,该块级格式化上下文决定了height:auto
(不设置height
时,其默认值为auto
)是如何计算的。
计算块级格式化上下文的高度时,浮动元素也参与计算。因此,父元素在计算其高度时,加入了浮动元素的高度,就达到了清理浮动的效果。
.one{
width: 300px;
margin-left: 50px;
/* float: left; */
overflow: hidden;
background-color: aquamarine;
}
.two{
width: 100px;
height: 100px;
float: left;
background-color: rgb(210, 70, 70);
}
4.父盒子里最下方引入清除浮动块
clear:both;是使它所在的块元素周围不允许有浮动,所有也可以起到消除塌陷的作用
不过单独添加一个清除浮动块有点冗余了
<body>
<div class="one">
<div class="two"></div>
<div class="three"></div>
</div>
</body>
.one{
width: 300px;
margin-left: 50px;
background-color: aquamarine;
}
.two{
width: 100px;
height: 100px;
float: left;
background-color: rgb(210, 70, 70);
}
.three{
clear: both;
}
5、为外部盒子添加after伪类,设置clear属性清除浮动。
zoom:1;作用:设置或检索对象的缩放比例,触发IE浏览器的haslayout属性,解决浮动, margin重叠等一些问题。
.one::after{
content: '';
clear: both;
display: block;
zoom: 1;
}