css的清除浮动的影响

分析HTML代码结构:

div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
</div>

   分析CSS代码样式:

.outer{border: 1px solid #ccc;background: #fc9;color: #fff; margin: 50px auto;padding: 50px;}
.div1{ 80px;height: 80px;background: red;float: left;}
.div2{ 80px;height: 80px;background: blue;float: left;}
.div3{ 80px;height: 80px;background: sienna;float: left;} 

这里我没有给最外层的DIV.outer 设置高度,但是我们知道如果它里面的元素不浮动的话,那么这个外层的高是会自动被撑开的。但是当内层元素浮动后,就出现了一下影响:

    (1):背景不能显示 (2):边框不能撑开 (3):margin 设置值不能正确显示

二、清除css浮动:

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

HTML:

<div class="outer">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <div class="clear"></div>
</div>

 CSS:

.clear{clear:both; height: 0; line-height: 0; font-size: 0}

 

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

HTML:

<div class="outer over-flow"> //这里添加了一个class
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <!--<div class="clear"></div>-->
</div>

  CSS:

.over-flow{
    overflow: auto; zoom: 1; //zoom: 1; 是在处理兼容性问题
}

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

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

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

                    .clearfix:after,.clearfix:before {
				display: block;
				content: ".";
				height: 0;
				line-height: 0;
				overflow: hidden;
				visibility: none;
				clear: both;
			}
			.clearfix {
				zoom:1; /*兼容ie7一下*/
			}

  

 

原文地址:https://www.cnblogs.com/suzhen-2012/p/5694755.html