前端——css浮动的影响与清除
子元素如果是浮动元素,那父元素一般不设置高度,可能造成布局混乱以后更改麻烦,不设置高度也会出现混乱
<div class="father">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
<div class="father2"></div>
*{
padding: 0;
margin: 0;
}
.father{
width: 1126px;
height: 300px;
}
.box1{
width: 200px;
height: 500px;
float: left;
background-color: red;
}
.box2{
width: 300px;
height: 200px;
float: left;
background-color: green;
}
.box3{
width: 400px;
float: left;
height: 100px;
background-color: blue;
}
.father2{
width: 1126px;
height: 600px;
background-color: purple;
}
消除影响
内墙法
用的少,在浮动元素最后加个div设置为clear:both清除浮动带来的影响
*{
padding: 0;
margin: 0;
}
.father{
width: 1126px;
}
.box1{
width: 200px;
height: 500px;
float: left;
background-color: red;
}
.box2{
width: 300px;
height: 200px;
float: left;
background-color: green;
}
.box3{
width: 400px;
float: left;
height: 100px;
background-color: blue;
}
.clear{
clear: both;
}
.father2{
width: 1126px;
height: 600px;
background-color: purple;
}
</style>
</head>
<body>
<div class="father">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<!-- 给浮动元素最后面加一个空的div 并且该元素不浮动 ,然后设置clear:both-->
<!-- 内墙法 -->
<!-- 无缘无故加了div元素 结构冗余 -->
<div class="clear"></div>
</div>
<div class="father2"></div>
</body>
</html>
伪元素清除法
利用伪元素after,在父元素后添加空内容,转换成块元素,本质还是在父元素内加了块元素。
<div class="clearfix">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
<div class="div2"></div>
*{
padding: 0;
margin: 0;
}
.clearfix{
width: 1126px;
}
.box1{
width: 200px;
height: 300px;
float: left;
background-color: red;
}
.box2{
width: 300px;
height: 100px;
float: left;
background-color: green;
}
.box3{
width: 400px;
float: left;
height: 50px;
background-color: blue;
}
/*必须要写这三句*/
.clearfix:after{
content:'';
clear:both;
display:block;
}
/*也这么写
.clearfix:after{
content: '.';
clear: both;
display: block;
height: 0;
visibility: hidden;
*/
.div2{
width: 1126px;
height: 400px;
background-color: purple;
}
overflow:hidden
<div class="div1">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
<div class="div2"></div>
https://blog.****.net/weixin_42359436/article/details/81183326