在文档流中,父元素的高度默认是被子元素撑开的,也就是子元素多高,父元素就多高.

但是当为子元素设置浮动以后,子元素会完全脱离文档流,此时将会导致子元素无法撑起父元素的高度,导致父元素的高度塌陷.由于父元素的高度塌陷了,则父元素下的所有元素都会向上移动,这样将会导致页面布局混乱.

解决办法:

  1.父元素设置overflow属性设置为hidden;

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>高度塌陷</title>
<style>
.parent {
background-color: #2aabd2;
overflow: hidden;
}

.children {
width: 100px;
height: 100px;
background-color: #8a6d3b;
float: left;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>

  2.给父元素设置:after伪类

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>高度塌陷</title>
<style>
.parent {
background-color: #2aabd2;
}

.parent:after {
content: '';
display: block;
clear: both;
}

.children {
width: 100px;
height: 100px;
background-color: #8a6d3b;
float: left;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>

相关文章:

  • 2021-11-19
  • 2021-10-08
  • 2021-11-30
  • 2020-03-01
  • 2021-09-30
  • 2021-11-01
  • 2021-12-10
  • 2021-08-27
猜你喜欢
  • 2020-04-02
  • 2021-10-16
  • 2018-12-24
  • 2021-09-13
  • 2021-11-29
  • 2018-09-17
  • 2021-11-07
  • 2021-09-21
相关资源
相似解决方案