什么是高度塌陷?
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.outer {}
.box1 {
width : 100px;
height : 200px;
background-color : #3030ff;
float :left;
}
.box2 {
width : 100px;
height : 100px;
background-color : red;
float : left;
}
</style>
</head>
<body>
<div class = "outer">
<div class = "box1"></div>
<div class = "box2"></div>
</div>
</body>
</html>
高度塌陷就是当子盒子浮动是,父盒子自适应高度为0.
解决这种高度塌陷有一下三种方法
①内墙法
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/**
添加一个样式,清楚浮动的影响
*/
.outer .fix{
clear : both;
}
.box1 {
width : 100px;
height : 200px;
background-color : #3030ff;
float :left;
}
.box2 {
width : 100px;
height : 100px;
background-color : red;
float : left;
}
</style>
</head>
<body>
<div class = "outer">
<div class = "box1"></div>
<div class = "box2"></div>
<div class = "fix"></div>
</div>
</body>
</html>
②给父元素添加overflow : hidden
.outer{
overflow : hidden;
}
③一些知名网站的解决方案(双伪元素浮动)
.outer:before,.outer:after {
content: "";
display: table;
}
.outer:after {
clear: both;
}
.outer {
*zoom: 1;
}
本文详细解释了在CSS布局中常见的高度塌陷问题,并提供了三种有效的解决方案:内墙法、使用overflow:hidden属性以及双伪元素浮动法。这些方法能够帮助开发者避免因子元素浮动导致的父元素高度为零的问题。
345

被折叠的 条评论
为什么被折叠?



