css清除浮动的几种方法

html-css06

css清除浮动的几种方法,第1张

1,父级div定义 height

<style type="text/css">

.div1{background:#000080border:1px solid red/*解决代码*/height:200px}

.div2{background:#800080border:1px solid redheight:100pxmargin-top:10px}

.left{float:leftwidth:20%height:200pxbackground:#DDD}

.rightright{float:rightrightwidth:30%height:80pxbackground:#DDD}

</style>

<div class="div1">

<div class="left">Left</div>

<div class="right">Right</div>

</div>

<div class="div2">

div2

</div>

原理:父级div手动定义height,就解决了父级div无法自动获取到高度的问题。

优点:简单,代码少,容易掌握

缺点:只适合高度固定的布局,要给出精确的高度,如果高度和父级div不一样时,会产生问题

建议:不推荐使用,只建议高度固定的布局时使用

评分:★★☆☆☆

2,结尾处加空div标签 clear:both

<style type="text/css">

.div1{background:#000080border:1px solid red}

.div2{background:#800080border:1px solid redheight:100pxmargin-top:10px}

.left{float:leftwidth:20%height:200pxbackground:#DDD}

.rightright{float:rightrightwidth:30%height:80pxbackground:#DDD}

/*清除浮动代码*/

.clearfloat{clear:both}

</style>

<div class="div1">

<div class="left">Left</div>

<div class="right">Right</div>

<div class="clearfloat"></div>

</div>

<div class="div2">

div2

</div>

3,父级div定义 伪类:after 和 zoom

<style type="text/css">

.div1{background:#000080border:1px solid red}

.div2{background:#800080border:1px solid redheight:100pxmargin-top:10px}

.left{float:leftwidth:20%height:200pxbackground:#DDD}

.rightright{float:rightrightwidth:30%height:80pxbackground:#DDD}

/*清除浮动代码*/

.clearfloat:after{display:blockclear:bothcontent:""visibility:hiddenheight:0}

.clearfloat{zoom:1}

</style>

<div class="div1 clearfloat">

<div class="left">Left</div>

<div class="right">Right</div>

</div>

<div class="div2">

div2

</div>

4,父级div定义 overflow:hidden

<style type="text/css">

.div1{background:#000080border:1px solid red/*解决代码*/width:98%overflow:hidden}

.div2{background:#800080border:1px solid redheight:100pxmargin-top:10pxwidth:98%}

.left{float:leftwidth:20%height:200pxbackground:#DDD}

.rightright{float:rightrightwidth:30%height:80pxbackground:#DDD}

</style>

<div class="div1">

<div class="left">Left</div>

<div class="right">Right</div>

</div>

<div class="div2">

div2

</div>

css浮动(float:none | left | right)在网页布局中我们经常使用的属性,也是经常会出现Bug的地方。

首先我们要搞清楚为什么要用到float呢?

网页布局中块级元素,在页面中独占一行,自上而下排列,也就是传说中的文档流。

可是我们要实现左右模块该怎么实现,这就需要用到float了,当我把第三个设置左浮动

然后我们在测试第四个也设置左浮动

下面我将第二个和第四个右浮动

我们在测试将第三个浮动取消

可是在做网页布局的时候不想浮动元素影响遮盖下一个元素该怎么解决?

这个时候就需要我们清除浮动(clear:both | left | right)

上面的例子 希望第三个左浮动,第二个和第四个右浮动,第五个不受影响在最下面。