1.产生的原因:
子元素使用float浮动属性,造成父级元素无法撑开。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{width:202px;border:1px solid #f35;}
.left{width:100px;height:100px;background:#0ec;float:left;}
.right{width:100px;height:100px;background:#fd3;float:right;}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
2.造成的影响:
1.父级元素内容无法撑开。
2.父级背景无法使用。
3.父级border边框无法使用。
4.父级margin,padding不能正确显示。
3.解决方案:
1.设置父级元素的高度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{width:202px;border:1px solid #f35;height:100px;}
.left{width:100px;height:100px;background:#0ec;float:left;}
.right{width:100px;height:100px;background:#fd3;float:right;}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>2.使用clear属性,在父级元素结尾添加clear:both子元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{width:202px;border:1px solid #f35;}
.left{width:100px;height:100px;background:#0ec;float:left;}
.right{width:100px;height:100px;background:#fd3;float:right;}
.clear{clear:both;}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="clear"></div>
</div>
</body>
</html>3.使用overflow属性,给父级元素设置overflow:hidden;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{width:202px;border:1px solid #f35;overflow:hidden;}
.left{width:100px;height:100px;background:#0ec;float:left;}
.right{width:100px;height:100px;background:#fd3;float:right;}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
4.使用:after伪类。为父级元素添加一伪类:after。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{width:202px;border:1px solid #f35;}
.left{width:100px;height:100px;background:#0ec;float:left;}
.right{width:100px;height:100px;background:#fd3;float:right;}
.container:after{clear:both;content:'';display:block;}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>4.效果图:
1087

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



