css清除浮动 clear float


clear float
1.为父元素添加overflow:hidden
第一个方法很简单,缺点是不太直观,即为父元素应用overflow:hidden,以强制它包围浮动元素。
eg.
<section>
    <img src = "images/rubber_duck2.jpg" />
    <p>It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>

section{border:1px solid blue; margin:0 0 10px 0; overflow:hidden;}
img{float:left;}
p{border:1px solid red;}
overflow:hidden;它能可靠的迫使父元素包含其浮动的子元素

2.同时浮动父元素

section{border:1px solid blue; float:left; width:100%;}
img{float:left;}
footer{border:1px solid red; clear:left;}

浮动section以后,不管其子元素是否浮动,它都会紧紧的包围住它的子元素。因此需要用width:100%再让section与浏览器容器同宽。另外,由于section现在也浮动了,所以footer会努力往上挤到它旁边去。为了强制footer依然待在section下方,要给它应用clear:left。被清除的元素不会被提升到浮动元素的旁边。

3.添加非浮动的清除元素

<section>
    <img src = "images/rubber_duck2.jpg" />
    <p>It's fun to float.</p>
    <div class = "clear_me"></div>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>

section{border:1px solid blue; float:left; width:100%;}
img{float:left;}
.clear_me{clear:left;}
footer{border:1px solid red; clear:left;}

这样,浮动的元素被父元素包围住了。
如果你特别不想添加这个纯表现性元素,我再告诉你一个用css来添加这个清除元素的方法。首先,要给section添加一个类。

<section class="clearfix">
    <img src = "images/rubber_duck2.jpg" />
    <p>It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>

然后,再使用这个神奇的clearfix的规则!

.clearfix:after{
    content:".";
    display:block;
    height:0;
    visibility:hidden;
    clear:both;
}

这个clearfix规则也叫伪元素清除法,它最早是由程序员Tony Aslett发明的,它只添加了一个清除的包含句点作为非浮动元素(必须有内容,而句点是最小的内容)。规则中的其他声明是为了确保这个伪元素没有高度,而且在页面上不可见。

此外,没有父元素时如何清除浮动

<section class="clearfix">
    <img src = "images/rubber_duck2.jpg" />
    <p class="clearfix">It's fun to float.</p>
    <img src = "images/rubber_duck2.jpg" />
    <p class="clearfix">It's fun to float.</p>
    <img src = "images/rubber_duck2.jpg" />
    <p class="clearfix">It's fun to float.</p>
</section>
<footer> Here is the footer element that runs across the bottom of the page.</footer>

给每一个段落都加上clearfix类,这样无论将来哪个段落的文本高度低于图片了,页面布局都不会被破坏


希望我的入坑经验对你有所帮助,愿圣光与你同在

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值