AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > css教程

浅谈css清除浮动(clearfix和clear)的用法

51自学网 http://www.51zixue.net
css,clearfix,clear

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

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

XML/HTML Code复制内容到剪贴板
  1. <!DOCTYPE HTML>  
  2. <html lang="en-US">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>如何在html中使用clearfix和clear</title>  
  6.     <link rel="stylesheet" type="text/css" href="/css/base.css" media="all"/>  
  7.     <style type="text/css">  
  8.     .fl{float:left;}   
  9.     .demo{background:#ccc;}   
  10.     .item1{background:#f90;height:100px;width:100px;}   
  11.     .item2{background:#fc0;height:200px;width:100px;}   
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <div class="demo">  
  16.         <div class="fl item1"></div>  
  17.         <div class="fl item2"></div>  
  18.     </div>  
  19. </body>  
  20. </html>  

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

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

XML/HTML Code复制内容到剪贴板
  1. <!DOCTYPE HTML>  
  2. <html lang="en-US">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>如何在html中使用clearfix和clear</title>  
  6.     <link rel="stylesheet" type="text/css" href="/css/base.css" media="all"/>  
  7.     <style type="text/css">  
  8.     .fl{float:left;}   
  9.     .demo{background:#ccc;}   
  10.     .item1{background:#f90;height:100px;width:100px;}   
  11.     .item2{background:#fc0;height:200px;width:100px;}   
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <h2>用 clear 清除浮动</h2>  
  16.     <div class="demo">  
  17.         <div class="fl item1"></div>  
  18.         <div class="fl item2"></div>  
  19.         <div class="clear"></div>  
  20.     </div>  
  21.     <h2>用 clearfix 清除浮动</h2>  
  22.     <div class="clearfix demo">  
  23.         <div class="fl item1"></div>  
  24.         <div class="fl item2"></div>  
  25.     </div>  
  26. </body>  
  27. </html>  

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

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

以上这篇浅谈css清除浮动(clearfix和clear)的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持51zixue.net。

原文地址:http://www.cnblogs.com/yjzhu/p/3227912.html


css,clearfix,clear  
上一篇:纯CSS实现鼠标悬停显示图片效果的实例分享  下一篇:彻底掌握CSS中的percentage百分比值使用