正常情况
如果子元素没有设置浮动(float),父元素的高度会随着子元素高度的改变而改变的。
设置浮动以后
父元素的高度不会随着子元素的高度而变化。
例如:在一个ul
中定义若干个li
,并设置float='left'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{margin: 0; padding: 0;}
.demo {
250px;
border: 1px solid #ccc;
padding: 10px;
margin: 20px auto;
}
li {
list-style: none outside none;
float: left;
height: 20px;
line-height: 20px;
20px;
border-radius: 10px;
text-align: center;
background: #f36;
color: green;
margin-right: 5px;
}
.demo * {
background: orange;
}
</style>
</head>
<body>
<ul class="demo">
<li class="first" id="first">1</li>
<li class="active">2</li>
<li class="important item" >3</li>
<li class="important" >4</li>
<li class="item">5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li class="last" id="last">10</li>
</ul>
</body>
</html>
显示结果就会是这样:
解决办法
- 最简单的方法是,给父元素增加
overflow:hidden
.demo {
250px;
border: 1px solid #ccc;
padding: 10px;
margin: 20px auto;
overflow: hidden;
}
- 在子元素的最后一个清除浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{margin: 0; padding: 0;}
.clearfix::after, .clearfix::before {
display: table;
content: '';
}
.clearfix::after {
clear: both;
overflow: hidden;
}
.demo {
250px;
border: 1px solid #ccc;
padding: 10px;
margin: 20px auto;
}
li {
list-style: none outside none;
float: left;
height: 20px;
line-height: 20px;
20px;
border-radius: 10px;
text-align: center;
background: #f36;
color: green;
margin-right: 5px;
}
.demo * {
background: orange;
}
</style>
</head>
<body>
<ul class="clearfix demo">
<li class="first" id="first">1</li>
<li class="active">2</li>
<li class="important item" >3</li>
<li class="important" >4</li>
<li class="item">5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li class="last" id="last">10</li>
</ul>
</body>
</html>