【css】清除浮动(clearfix 和 clear)的用法

来源:互联网 发布:websocket nginx 转发 编辑:程序博客网 时间:2024/05/21 05:24

转自:http://www.cnblogs.com/yjzhu/archive/2013/07/31/3227912.html


本文主要是讲解如何在 html 中使用 clearfix 和 clear,针对那些刚开始了解 css 的童鞋。关于 clearfix 和 clear 的样式在这里我就不写了,具体样式点击此处

下面就谈谈对于这两个 class 的用法,首先我们先看个例子:

复制代码
<!DOCTYPE HTML><html lang="en-US"><head>    <meta charset="UTF-8"/>    <title>如何在html中使用clearfix和clear</title>    <link rel="stylesheet" type="text/css" href="/css/base.css" media="all"/>    <style type="text/css">    .fl{float:left;}    .demo{background:#ccc;}    .item1{background:#f90;height:100px;width:100px;}    .item2{background:#fc0;height:200px;width:100px;}    </style></head><body>    <div class="demo">        <div class="fl item1"></div>        <div class="fl item2"></div>    </div></body></html>
复制代码

我们都知道使用浮动会产生很多未知的问题,通过上面的例子我们可以发现 class="demo" 的高度并没有被里面的 div 给撑开,这是因为里面的 div 产生浮动而脱离了该文档,因为 demo 本身没有高度,所以我们看不到它的灰色背景。当然只要给 demo 一个高度就行了,但是这就脱离了本文的目的(有时我们希望外层 div 的高度由里面的内容来决定)。

既然是浮动产生的问题,那么只要清除浮动就可以了,相信高手们有很多清除浮动的方法,比如 overflow:hidden。下面我将介绍用 clearfix 和 clear 来清除浮动。

复制代码
<!DOCTYPE HTML><html lang="en-US"><head>    <meta charset="UTF-8"/>    <title>如何在html中使用clearfix和clear</title>    <link rel="stylesheet" type="text/css" href="/css/base.css" media="all"/>    <style type="text/css">    .fl{float:left;}    .demo{background:#ccc;}    .item1{background:#f90;height:100px;width:100px;}    .item2{background:#fc0;height:200px;width:100px;}    </style></head><body>    <h2>用 clear 清除浮动</h2>    <div class="demo">        <div class="fl item1"></div>        <div class="fl item2"></div>        <div class="clear"></div>    </div>    <h2>用 clearfix 清除浮动</h2>    <div class="clearfix demo">        <div class="fl item1"></div>        <div class="fl item2"></div>    </div></body></html>
复制代码

我们发现,clearfix 主要是用在浮动层的父层,而 clear 主要是用在浮动层与浮动层之间,和浮动层同一级,如果想要撑开父层的高度,clear 就要放在最后。

很难说明这两个方法哪个更好,只能说具体需求具体对待。

也许有人会问,clearfix 的样式这样写为什么会清除浮动?这些样式都有什么意义?这需要童鞋们对 css 的伪类有一定的了解,具体内容请点击《闲聊CSS之关于clearfix——清除浮动》


0 0