您的位置:首页 > Web前端 > CSS

css 清除元素的浮动方法总结

2016-08-02 15:28 639 查看
        1、首先说下为什么要清除浮动。

        因为元素在浮动后会脱离文档流,从而使父元素感受不到它的高度,不能自己撑开。效果如下图:


        2、接下来就来学习下,清除浮动的三种方法:

                ①在浮动元素后面添加div,然后给div设置的样式设置 clear:both;代码如下

                

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>浮动</title>
<style>
div{margin: 2px;}
.box{
border: 1px solid green; width: 550px;
}
.float{
width: 100px; height: 100px; background: red;
float: left;
}
.clear{
clear: both;
}
</style>
</head>
<body>
<div class="box">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="clear"></div>
</div>
</body>
</html>


                ②给浮动元素的父级的样式添加overflow:hidden;代码如下:

             

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>浮动</title>
<style>
div{margin: 2px;}
.box{
border: 1px solid green; width: 550px; overflow: hidden;
}
.float{
width: 100px; height: 100px; background: red;
float: left;
}
</style>
</head>
<body>
<div class="box">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
</div>
</body>
</html>


                ③使用伪类清除浮动,这也是最好的一种清除方式,具体代码如下:

                

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>浮动</title>
<style>
div{margin: 2px;}
.box{
border: 1px solid green; width: 550px;
}
.float{
width: 100px; height: 100px; background: red;
float: left;
}
/*伪类代码*/
.box:after{
content: ''; display: block;
clear: both; display: none;
}
</style>
</head>
<body>
<div class="box">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
</div>
</body>
</html>


        清除完浮动后效果如下:

       
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息