服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - 编程技术 - 浅谈css清除浮动(clearfix和clear)的用法

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

2023-05-17 11:43yjzhu 编程技术

下面小编就为大家带来一篇浅谈css清除浮动(clearfix 和clear)的用法,小编觉得挺不错的,现在就分享给大家,也给大家做个参考,一起跟随小编过来看看吧

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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 来清除浮动。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!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 就要放在最后。

当前比较常用的

?
1
2
3
.clearfix:after{content:'\20';display:block;height:0;clear:both}
.clearfix{zoom:1}
.clear{clear:both;height:0;line-height:0;font-size:0;visibility:hidden;overflow:hidden}

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

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

延伸 · 阅读

精彩推荐