CSS清除浮动的方法

  CSS清除浮动的方法有哪些呢?常常性地会使用到float,不少邪门的事儿都有多是浮动在做怪,清除浮动是必需要作的,并且随时性地对父级元素清除浮动的作法也被认为是书写CSS的良好习惯之一。
下面看今天的教程,此为未清除浮动源代码,运行代码没法查看到父级元素浅黄色背景。css

<style type=”text/css”>
<!–
    *{margin:0;padding:0;}
    body{font:36px bold; color:#F00; text-align:center;}
    #layout{background:#FF9;}
    #left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
    #right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
    <div id=”left”>Left</div>
    <div id=”right”>Right</div>
</div>浏览器

 

 

1、使用空标签清除浮动对象

  我用了好久的一种方法,空标签能够是div标签,也能够是P标签。我习惯用<div>,够简短,也有不少人用<hr>,只是须要另外为其清除边框,但理论上能够是任何标签。这种方式是在须要清除浮动的父级元素内部的全部浮动元素后添加这样一个标签清楚浮动,并为其定义CSS代码:clear:both。此方法的弊端在于增长了无心义的结构元素。
<style type=”text/css”>
<!–
    *{margin:0;padding:0;}
    body{font:36px bold; color:#F00; text-align:center;}
    #layout{background:#FF9;}
    #left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
    #right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
    .clr{clear:both;}
–>
</style>
<div id=”layout”>
    <div id=”left”>Left</div>
    <div id=”right”>Right</div>
    <div class=”clr”></div>
</div>教程

2、使用overflow属性utf-8

  此方法有效地解决了经过空标签元素清除浮动而不得不增长无心代码的弊端。使用该方法是只需在须要清除浮动的元素中定义CSS属性:overflow:auto,便可!”zoom:1″用于兼容IE6。get

<style type=”text/css”>
<!–
    *{margin:0;padding:0;}
    body{font:36px bold; color:#F00; text-align:center;}
    #layout{background:#FF9;overflow:auto;zoom:1;}
    #left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
    #right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
    <div id=”left”>Left</div>
    <div id=”right”>Right</div>
</div>it

3、使用after伪对象清楚浮动class

  该方法只适用于非IE浏览器。具体写法可参照如下示例。使用中需注意如下几点。1、该方法中必须为须要清除浮动元素的伪对象中设置height:0,不然该元素会比实际高出若干像素;2、content属性是必须的,但其值能够为空,蓝色理想讨论该方法的时候content属性的值设为”.”,但我发现为空亦是能够的。float

<style type=”text/css”>
<!–
    *{margin:0;padding:0;}
    body{font:36px bold; color:#F00; text-align:center;}
    #layout{background:#FF9;}
    #layout:after{display:block;clear:both;content:”";visibility:hidden;height:0;}
    #left{float:left;width:20%;height:200px;background:#DDD;line-height:200px;}
    #right{float:right;width:30%;height:80px;background:#DDD;line-height:80px;}
–>
</style>
<div id=”layout”>
    方法

相关文章
相关标签/搜索