css clear float 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类,这样无论将来哪个段落的文本高度低于图片了,页面布局都不会被破坏


I hope my experience of entering the pit is helpful to you, may the Holy Light be with you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324349342&siteId=291194637