有效清浮动方法

来源:互联网 发布:程序员入门到入狱 编辑:程序博客网 时间:2024/05/07 23:58

在搭建页面的过程当中,经常用到左浮动、右浮动,但有时一些浮动的效果会影响这个页面,那么如果有效并简单得清楚浮动呢?

首先,我们搭建一个页面,大致构思是这样的,头部、内容区、尾部,其中内容区则是以左右两部分组成。

代码如下:

<div id="header"></div><div id="content" class="clear">    <div class="left"></div>    <div class="right"></div></div><div id="footer"></div>

为其添加简单的样式:

body { margin:0; }#header { width:100%; height:100px; background:red; }#content { width:80%; height:auto; margin:10px auto; }#content .left, #content .right { float:left; }#content .left { width:40%; height:200px; background:pink;  }#content .right { width:60%; height:400px; background:yellow;  }#footer { width:100%; height:100px; background:gray; }

那我们就能得到如下的页面:

我们可以清楚得看到底部的footer上移了,破坏了整个的布局,接下来,我们进行浮动的清楚。

代码如下:

.clear { zoom:1; }.clear:after { content:''; display:block; clear:both; }

我们将这个clear样式加到left以及right的父级上,也就是“content”上,

<div id="content" class="clear">

接下来我们看下清楚浮动的效果:


现在整个页面的布局都正常了。

清楚浮动的方式有很多:包括加高、父级浮动、inline-block、空标签清浮动、br清浮动、overflow清浮动等等。

而上面这种清浮动的方式叫做after伪类清浮动方法,这种方式的重用性很高,很方便实用。

完整的代码如下:

<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title><style>body { margin:0; }#header { width:100%; height:100px; background:red; }#content { width:80%; height:auto; margin:10px auto; }#content .left, #content .right { float:left; }#content .left { width:40%; height:200px; background:pink;  }#content .right { width:60%; height:400px; background:yellow;  }#footer { width:100%; height:100px; background:gray; }/*清除浮动*/.clear { zoom:1; }.clear:after { content:''; display:block; clear:both; }</style></head><body>    <div id="header"></div>    <div id="content" class="clear">    <div class="left"></div>        <div class="right"></div>    </div>    <div id="footer"></div></body></html>

0 0