清除浮动的几种方法

浮动是布局中经常采用的手段,但是浮动带来的高度塌陷却为布局带来麻烦,所以我们经常需要清除浮动,下文记录几种常用的清除浮动手段

高度塌陷:

clear属性

第一种运用clear的方式在需要清浮动的元素下放一个div,并加上clear:both
html

        <div class="content" >
        <div class='float'></div>
        </div>	
        <div class='clear'></div>
	<p>some text</p>
复制代码

css

               .float{
			width:300px;height:300px;
			float:left;
			background: green;
			opacity: .5;
		}
		p{
			background:red;
		}
		.clear{
		    clear:both;
		}
复制代码

第二种方式是用伪元素:before:after
html

        <div class="content" >
         <div class='float'></div>
        </div>	
	<p>some text</p>
复制代码

css

             .content:after{
                   content:'';
                   display:'block';
                   clear:both;
               }
              float{
			width:300px;height:300px;
			float:left;
			background: green;
			opacity: .5;
		}
		p{
			background:red;
		}
复制代码

overflow:hidden

该方法利用了BFC的特性,当元素有以下特性时,触发BFC

  • html根元素
  • float的值不为none
  • overflow的值为hidden、auto或scroll
  • position的值不为staticrelative
  • display的值为table-celltable-caption、或inline-block

html

       <div class="content" >
		<div class="float"></div>
	</div>	
	<p>some text</p>
复制代码

css

               .content{
			overflow: hidden;
		}
		.float{
			float:left;
			width:100px;height:100px;
			background: green;
			opacity: .5;
		}
		p{
			background:red;
		}
复制代码

清除浮动效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值