正常情況
如果子元素沒有設置浮動(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 {
width: 250px;
border: 1px solid #ccc;
padding: 10px;
margin: 20px auto;
}
li {
list-style: none outside none;
float: left;
height: 20px;
line-height: 20px;
width: 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 {
width: 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 {
width: 250px;
border: 1px solid #ccc;
padding: 10px;
margin: 20px auto;
}
li {
list-style: none outside none;
float: left;
height: 20px;
line-height: 20px;
width: 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>