float浮动,父级元素边框塌陷问题
当我们使用float浮动子元素时,肯定会影响父元素的边框。父级元素边框塌陷的原因是,当父元素没有设置足够的大小时,父元素的高度是由父元素中最高子元素的高度决定的。一旦子元素浮动,脱离了文档流不再占据原本的位置,父元素中没有非浮动的可见子元素,父元素的高度就会塌陷。
如下代码所示:
HTML代码
<div class="father"> <div class="son"> </div> </div>
CSS代码
.father{
width: 200px;
background-color: red;
}
.son{
width: 75px;
height: 50px;
background-color: #008000;
float: left;
}
运行结果

解决方案:
一:给父元素设置固定高度,这种方式不推荐使用,太不灵活。
.father{
width: 200px;
height: 200px;
background-color: red;
}
.son{
width: 75px;
height: 50px;
background-color: #008000;
float: left;
}

二:给父元素设置overflow:hidden

三:在父元素后面加个div,设置属性clear:both
<style type="text/css"> .father{ width: 200px; background-color: red; } .clear{ clear: both; } .son{ width: 75px; height: 50px; background-color: #008000; float: left; } </style> <div class="father"> <div class="son"> </div> <div class="clear"> </div> </div>
效果和方式二是一样的,但是不推荐使用因为会造成代码冗余。
四:使用伪类after
<style type="text/css"> .father{ width: 200px; background-color: red; } .father::after{ content: ""; display: block; clear: both; } .son{ width: 75px; height: 50px; background-color: #008000; float: left; } </style> <div class="father"> <div class="son"> </div> </div>
这种方式本质上和方式三一样,但是没有后遗症。

浙公网安备 33010602011771号