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

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

XML/HTML 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>       <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 来清除浮动。

XML/HTML 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 就要放在最后。

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

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

原文地址:http://imgbuyun.weixiu-service.com/up79/202309/vq2se4mp0lk.html

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