最小高度为100px的父元素,嵌套一个300px高度的子元素,当子元素浮动时,父元素高度并不随之升高。在某些特殊的条件下,为子元素设置上外边距时,有可能会作用到父元素上。
1. 子元素浮动导致父元素高度不够
<!DOCTYPE html>
<html>
<head>
<title>1</title>
<meta charset="utf-8">
<style type="text/css">
.d0{width: 300px;background: #336;min-height: 100px;}
.d1{float: right;width: 200px;background: #289;height: 200px;opacity: 0.5}
</style>
</head>
<body>
<div class="d0">
<div class="d1">我是浮动的子元素</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>1</title>
<meta charset="utf-8">
<style type="text/css">
.d0{width: 300px;background: #336;min-height: 100px;}
.d1{float: right;width: 200px;background: #289;height: 200px;opacity: 0.5}
/*解决问题的代码*/
.clear:after{content:"";display:block;clear:both;}
</style>
</head>
<body>
<div class="d0">
<div class="d1">我是浮动的子元素</div>
<div class="clear"></div>
</div>
</body>
</html>
2.子元素浮动导致外边距溢出
<!DOCTYPE html>
<html>
<head>
<title>2</title>
<meta charset="utf-8">
<style type="text/css">
.d1{width: 300px;height: 100px;background: #336}
.d2{width: 300px;height: 100px;background: #289}
.d2son{width: 150px;height: 50px;background: #caa;opacity: 0.5;margin-top: 50px;}
</style>
</head>
<body>
<div class="d1">上面的div</div>
<div class="d2">
<div class="d2son">下面的div的子元素</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>2</title>
<meta charset="utf-8">
<style type="text/css">
.d1{width: 300px;height: 100px;background: #336}
.d2{width: 300px;height: 100px;background: #289}
.d2son{width: 150px;height: 50px;background: #caa;opacity: 0.5;margin-top: 50px;}
/*解决问题的代码*/
.d2:before {content:"";display:table;}
</style>
</head>
<body>
<div class="d1">上面的div</div>
<div class="d2">
<div class="d2son">下面的div的子元素</div>
</div>
</body>
</html>