CSS清除因为浮动布局导致父元素height值为0的三种方法

20 篇文章 0 订阅
15 篇文章 0 订阅

在使用css布局页面的时候往往会使用float布局元素,这时有可能会出现因为浮动,父元素出现高度为0的情况,如图所示
这里写图片描述
这时会根据项目需要对浮动的元素进行清除,以避免父元素出现为高度0的情况。常见的方法如下:

第一种 、<div class="clearboth"></div>
这里写图片描述

在子元素里面多加一个div(或者其他带有clear:both样式的元素)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
		#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
		
		.clearboth{clear:both;height:0;}
    </style>
</head>
<body>
    <div class="ob" id="od">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="clearboth"></div>
    </div>
</body>
</html>

第二种、伪类::after清除方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
		#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
		
		#od::after{content:"";display:block;clear:both;}
		
    </style>
</head>
<body>
    <div class="ob" id="od">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
    </div>
</body>
</html>

第三种、使用overflow属性进行清除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
		#od>div{float:left;height:100px;width:100px;margin:0 10px;background:#ccc;}
		#od{overflow:auto;}/***设置hidden也可以**/
    </style>
</head>
<body>
    <div class="ob" id="od">
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		
    </div>
</body>
</html>

第一种则会在项目中多加了一个无用的dom元素,一般情况出现的少,第二种使用css伪类在一些比较低版本的浏览器中可能会出现兼容性问题,第三种使用overflow属性也有存在的弊端,比如如果如长度超出了会出现隐藏等现象,所以一般在项目中使用第二种居多,可以兼容大部分用户浏览器。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值