清除浮动的三种方法

来源:互联网 发布:wps表格数据无法求和 编辑:程序博客网 时间:2024/05/28 11:50

 方法一:添加新的元素 、应用 clear:both;

<html>
<head>
<style>
.outer{border: 1px solid #fff;background: #fc9;color: #fff;margin: 50px auto;padding: 50px;}
.div1{width:80px;height:80px;background:red;float:left;}
.div2{width:80px;height:80px;background:blue;float:left;}
.div3{width:80px;height:80px;background:sienna;float:left;}
.clear{clear:both; height: 0; line-height: 0; font-size: 0}
</style>
</head>
<body>
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="clear"></div>
</div>
</body>
</html>

方法二:父级div定义 overflow: auto注意:是父级div也就是这里的  div.outer

原理:使用overflow属性来清除浮动有一点需要注意,overflow属性共有三个属性值:hidden,auto,visible。我们可以使用hiddent和auto值来清除浮动,但切记不能使用visible值,如果使用这个值将无法达到清除浮动效果,其他两个值都可以,其区据说在于一个对seo比较友好,另个hidden对seo不是太友好,其他区别我就说不上了,也不浪费时间。

<html>
<head>
<style>
.outer{border: 1px solid #fff;background: #fc9;color: #fff;margin: 50px auto;padding: 50px;}
.div1{width:80px;height:80px;background:red;float:left;}
.div2{width:80px;height:80px;background:blue;float:left;}
.div3{width:80px;height:80px;background:sienna;float:left;}
.clear{clear:both; height: 0; line-height: 0; font-size: 0}
.over-flow{overflow:auto;zoom:1; //zoom: 1; 是在处理兼容性问题}
</style>
</head>
<body>
<div class="outer over-flow">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<!--<div class="clear"></div>-->
</div>
</body>
</html>

 方法三: 据说是最高大上的方法  :after 方法:(注意:作用于浮动元素的父亲)

先说原理:这种方法清除浮动是现在网上最拉风的一种清除浮动,他就是利用:after和:before来在元素内部插入两个元素块,从面达到清除浮动的效果。其实现原理类似于clear:both方法,只是区别在于:clear在html插入一个div.clear标签,而outer利用其伪类clear:after在元素内部增加一个类似于div.clear的效果。

其中clear:both;指清除所有浮动;content: '.'; display:block;对于FF/chrome/opera/IE8不能缺少,其中content()可以取值也可以为空。visibility:hidden;的作用是允许浏览器渲染它,但是不显示出来,这样才能实现清楚浮动。

<html>
<head>
<style>
.outer{ 

        border: 1px solid green;
        padding: 5px;
        margin: 5px;
        
      }
.outer:after {clear:both;content:'.';display:block;width: 0;height: 0;visibility:hidden;}
.div1{width:80px;height:80px;background-color:red;float:left;}
.div2{width:80px;height:80px;background-color:blue;float:left;}
.div3{width:80px;height:80px;background-color:red;float:left;}
</style>
</head>
<body>
<div class="outer">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
</body>
</html>

当一个内层元素是浮动的时候,如果没有关闭浮动时,其父元素也就不会再包含这个浮动的内层元素,因为此时浮动元素已经脱离了文档流。也就是为什么外层不能被撑开了!

原创粉丝点击