css如何清除浮动?

html-css013

css如何清除浮动?,第1张

css清除浮动可以理解为打破横向排列。 清除浮动的关键字是clear,官方定义如下: 语法: clear : none | left | right | both 取值: none : 默认值。允许两边都可以有浮动对象 left : 不允许左边有浮动对象 right : 不允许右边有浮动对象 both : 不允许有浮动对象 根据上边的基础,假如页面中只有两个元素div1、div2,它们都是左浮动,场景如下:此时div1、div2都浮动,根据规则,div2会跟随在div1后边,但仍然希望div2能排列在div1下边,就像div1没有浮动,div2左浮动那样。这时候就要用到清除浮动(clear)对于CSS的清除浮动(clear),一定要牢记:这个规则只能影响使用清除的元素本身,不能影响其他元素。具体做法:要想让div2下移,就必须在div2的CSS样式中使用浮动。本例中div2的左边有浮动元素div1,因此只要在div2的CSS样式中使用clear:left来指定div2元素左边不允许出现浮动元素,这样div2就被迫下移一行。

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>