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

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

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

<!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 的高度由里面的内容来决定)。spa

既然是浮动产生的问题,那么只要清除浮动就能够了,相信高手们有不少清除浮动的方法,好比 overflow:hidden。下面我将介绍用 clearfix 和 clear 来清除浮动。code

<!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 就要放在最后。htm

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

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

相关文章
相关标签/搜索