一、什么是盒子塌陷
情况一:当子元素设置外边距,导致父元素连带向下,这就导致盒子模型塌陷
情况二:当父元素未设置高度,此时父元素的高度取决于子元素的高度,当子元素设置浮动后,会脱离文档流,造成子元素的内容在父元素外出现。
脱离文档流:在HTML中块级元素一个一排自上往下堆放,行内元素自左往右堆放,而脱离文档流就是不遵循这套标准,元素于元素之间开始堆叠。
二、解决办法
情况一示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子塌陷1</title>
<style>
*{
margin: 0; // 设置元素的外边距为0。
padding: 0; //设置元素的内边距为0。
box-sizing: border-box; //并排放置两个带边框的框
}
.one{
width: 400px;
height: 400px;
background-color: green;
}
.two{
width: 200px;
height: 200px;
background-color: yellow;
margin-top: 100px; /*设置元素的上外边距。*/
margin-left: 100px; /*设置元素的左外边距。*/
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
</html>
原本是想呈现这样的效果:
可是实际上发生了盒子塌陷,变成了这样 :
可以看到父元素被拉扯了下来,解决方案如下:
.one{
width: 400px;
height: 400px;
background-color: green;
/*1.给父元素加上边框*/
border: 1px solid;/*border定义边框 solid--实线*/
/*2.给父元素设置上内边距*/
padding-top: 1px; /*注意:此时父盒子高度为400px+1px*/
/*3.给父元素加上overflow:hidden*/
overflow: hidden; /*overflow 属性规定当内容溢出元素框时发生的事情。hidden 内容会被修剪,并且其余内容是不可见的。*/
/*4.给子盒子或父盒子加一个浮动*/
/*4.1父盒子加浮动*/
float: left;
/*5.给父元素或子元素加上绝对定位*/
/*5.1给父元素添加绝对定位*/
position: absolute; /*position 属性规定元素的定位类型。*/
}
.two{
width: 200px;
height: 200px;
background-color: yellow;
margin-top: 100px; /*设置元素的上外边距。*/
margin-left: 100px; /*设置元素的左外边距。*/
/*4.2给子盒子加浮动*/
float: left;
/*5.2给子元素加上绝对定位*/
position: absolute;
}
上述的方式任选一种即可解决该种情况的盒子塌陷问题。
情况二示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子塌陷2</title>
<style>
.one{
background-color: green;
}
.two{
width: 200px;
height: 200px;
background-color: yellow;
float: left;
}
.three{
height: 200px;
background-color: #50afeb;
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
<div class="three"></div>
</body>
</html>
由于父元素未设置高度,所有父元素的高度由子元素决定,所以应该呈现的效果为:
但是由于子元素添加了浮动,所以效果变为下图:
可以看到子元素以脱离文档流,使父元素没有了高度支撑而消失,造成了父元素的高度塌陷。从而导致页面布局混乱。
解决方法:
①给父元素设置高度,设置的高度需大于等于子元素
②在父元素中使用after清除浮动(最常用)。代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子塌陷2</title>
<style>
.one{
background-color: green;
}
.clearfix{
zoom: 1;
}
.one:after{
content: '';/*伪元素,内容为空*/
display: table;/*规定元素应该生成的框的类型,此处只要不为默认就行*/
clear: both;/*清除浮动*/
}
.two{
width: 200px;
height: 200px;
background-color: yellow;
float: left;
}
.three{
height: 200px;
background-color: #50afeb;
}
</style>
</head>
<body>
<div class="one clearfix">
<div class="two"></div>
</div>
<div class="three"></div>
</body>
</html>
③在父元素的最下方添加<br style="clear: both">清除浮动块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>盒子塌陷2</title>
<style>
.one{
background-color: green;
}
.two{
width: 200px;
height: 200px;
background-color: yellow;
float: left;
}
.three{
height: 200px;
background-color: #50afeb;
}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
<br style="clear: both">
</div>
<div class="three"></div>
</body>
</html>