盒子模型-高度塌陷问题
相邻兄弟塌陷问题
给两个是兄弟关系的div的外边距都设置为20px,让第一个div的浮动,第二个div左边距和第一个div的宽度相同。由于第一个div浮动脱离了文档流,所以这样会造成两个div对不齐,如下图。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#div1{
width: 300px;
height: 300px;
background-color: aquamarine;
margin-top: 20px;
float: left;
}
#div2{
width: 300px;
height: 300px;
background-color:brown;
margin-top: 20px;
margin-left: 300px;
}
</style>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
解决方法
给这两个div添加一个父div,并设置父div的上边框,如下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#div1{
width: 300px;
height: 300px;
background-color: aquamarine;
margin-top: 20px;
float: left;
}
#div2{
width: 300px;
height: 300px;
background-color:brown;
margin-top: 20px;
margin-left: 300px;
}
.div3{
border-top: white solid 1px;
clear: both;
}
</style>
<body>
<div class="div3">
<div id="div1"></div>
<div id="div2"></div>
</div>
</body>
</html>
使用margin-top时造成塌陷
使用margin-top造成的塌陷是由于当标签出现父子关系,给子元素添加margin-top属性,让它距离父盒子顶部50px时,却出现父元素距离边框50px。如下:
<style>
.div1{
width: 600px;
height: 600px;
background-color: aquamarine;
}
.div2{
width: 300px;
height: 300px;
background-color: red;
margin-top: 50px;
}
</style>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
不设置margin-top时,盒子的显示情况
设置margin-top时,盒子的显示情况
使用margin-top时造成塌陷解决方案
1、给父元素添加边框属性,让父元素的边框颜色和浏览器的背景颜色一样。如下:
给第一个div(div1)添加border属性。
border: white solid 1px;
2、给父元素添加浮动属性(float)
虽然这种方法可以解决margin-top造成塌陷问题,但是float属性可能会带来一些其他未知的问题,所以不建议使用float来解决margin-top造成塌陷问题。
给第一个div(div1)添加float: left;
3、溢出隐藏
在父元素的style里面添加overflow:hidden;
给第一个div(div1)添加verflow:hidden。
.div1{
width: 600px;
height: 600px;
background-color: aquamarine;
overflow: hidden;
}
4、给父元素设置display:table;
此元素会作为块级表格来显示,表格前后带有换行符。
.div1{
width: 600px;
height: 600px;
background-color: aquamarine;
display: table;
}
5、给父元素添加position:fixed;
生成绝对定位的元素,相对于浏览器窗口进行定位。
元素的位置通过 “left”, “top”, “right” 以及 “bottom” 属性进行规定。
.div1{
width: 600px;
height: 600px;
background-color: aquamarine;
position: fixed;
}
6、给父类添加伪元素
给父类添加伪元素,其用法、表现形式和真正元素的用法一样
.box-div1::before{
content: ' '; /*内容为空*/
display: table;
}
<style>
.div1{
width: 600px;
height: 600px;
background-color: aquamarine;
}
.div2{
width: 300px;
height: 300px;
background-color: red;
margin-top: 50px;
}
.box-div1::before{
content: '';
display: table;
}
</style>
<body>
<hr color="black">
<div class="div1 box-div1">
<div class="div2"></div>
</div>
</body>
参考:塌陷问题