以下代码会导致浮动问题,如下图,因为child1和child2是浮动的不能撑开父容器的大小.father的背景颜色会因为没有宽高而不能显示。
<html>
<head>
<style>
.father{
background:#ccc;
}
.child1{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.child2{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
</div>
</body>
</html>
</pre><p><img src="https://img-blog.youkuaiyun.com/20160614102816864?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></p><p>1、清除浮动方法一-----使用空标签清除浮动</p><p><span style="white-space:pre"></span>在要清除浮动的元素的内部所有浮动元素的后面添加div或其他block的标签,并给改标签添加clear:both的css样式,代码如下,此方法对FF、chrom、IE下均有效</p><p><span style="white-space:pre"></span>弊端:给页面增加了无意义的结构</p><p></p><pre name="code" class="html"><html>
<head>
<style>
.father{
background:#ccc;
}
.child1{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.child2{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.clear{
clear:both;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
<div class="clear"></div>
</div>
</body>
</html>
2、清除浮动的方法二-----使用overflow属性
给要清除浮动的元素添加overflow;hidden;或overflow:auto;并添加zoom:1;或width:100%;兼容IE,代码如下
<html>
<head>
<style>
.father{
background:#ccc;
overflow:auto;/*可用overflow:hidden;代替*/
zoom:1;/*可用width:100%代替*/
}
/*.father:after{*/
/*display:block;*/
/*content:'';*/
/*clear:both;*/
/*}*/
.child1{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.child2{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
/*.clear{*/
/*clear:both;*/
/*}*/
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
<!--<span class="clear"></span>-->
</div>
</body>
</html>
3、清除浮动的方法三-----使用after伪类选择器
给要清除浮动的元素添加after伪类css样式
<!doctype html>
<html>
<head>
<style>
.father{
background:#ccc;
zoom:1;/*兼容IE也可以用width:100%;*/
}
.father:after{
display:block;
content:'';/*如果用content:'.'会在底部多出若干像素r*/
clear:both;
}
.child1{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.child2{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
</div>
</body>
</html>
4、清除浮动的方法四-----浮动父级元素
给父级元素添加float属性,该方法的弊端是会影响父级标签的下一个元素的位置,并且此方法因为父标签浮动所以不再占整行
<!doctype html>
<html>
<head>
<style>
.father{
background:#ccc;
float:left;
}
.child1{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
.child2{
width:200px;
height:200px;
border:3px solid #00D0BC;
float:left;
}
</style>
</head>
<body>
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
</div>
</body>
</html>
前三种方法效果
第四种方法效果