没有围住浮动元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
section{
border:1px solid #0f0;
margin: 0 0 10px 0;
}
p{
margin: 0 0 10px 0;
border:1px solid blue;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
footer{
border:1px solid red;
}
</style>
</head>
<body>
<section>
<img src="img/1.png"/>
<p>jQuery is a fast.
</p>
</section>
<footer>
Query has changed the way that millions of people write JavaScript.
</footer>
</body>
</html>
浮动图片之后标题跑到右边,但父元素section也收缩到只包含文本的高度
妈呀!!!
标题倒是跑到右边了,可section也不再保温浮动元素了,它只包围非浮动元素。于是footer被提上来了,紧挨着前一个块级元素——section。
- 方法一:为父元素添加overflow:hidden
section{
border:1px solid #0f0;
margin: 0 0 10px 0;
overflow: hidden;
}
结果:
overflow:hidden能可靠的迫使父元素包含其浮动元素
2 . 方法二:同时浮动父元素
让父元素也包含其浮动子元素的第二个方法就是让父元素也浮动起来。
section{
border:1px solid #0f0;
margin: 0 0 10px 0;
float: left;width: 100%;
}
p{
margin: 0 0 10px 0;
border:1px solid blue;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
footer{
border:1px solid red;
}
浮动section之后,不管它的子元素否浮动,它都会紧紧包围(收缩)住它的子元素
footer尽然跑上来了!!!
由于section浮动,footer会往上挤到它旁边。
解决办法:就是给footer应用clear:left,被清除的元素不会提升到浮动元素旁边
3.方法三:添加非浮动的清除元素
给父元素的最后添加一个非浮动的子元素,然后清除该子元素。
原理:由于包含元素一定会包围非浮动的子元素,而且清除会让这个子元素位于(清除的一侧)浮动元素的下方,因此包含元素一定会包含这个子元素以及前面浮动的元素。
有两种方式
- 简单的添加一个子元素,并给它应用clear属性。没有默认属性的div元素很适合这个角色。
<style>
section{
border:1px solid #0f0;
margin: 0 0 10px 0;
width: 100%;
}
p{
margin: 0 0 10px 0;
border:1px solid blue;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
.clear_me{
clear:left;
}
...
<section>
<img src="img/1.png"/>
<p>jQuery is a fast.
</p>
<div class="clear_me"></div>
</section>
- 只添加了一个清除的包含句点的非浮动元素(必须要有内容,而句点是最小内容)
规则中的声明是为了让这个伪元素没有高难度,同时在页面上是不可见的。
section{
border:1px solid #0f0;
margin: 0 0 10px 0;
width: 100%;
}
p{
margin: 0 0 10px 0;
border:1px solid blue;
}
img{
float: left;
margin:0 5px;
width:50px;
height: 80px;
}
.clearfix:after{
content: ".";
display: block;
height: 0;
/*设为0不然会占空间比如20px,虽然不显示但会占据20px的位置*/
visibility: hidden;/*句点不显示*/
/*display: none;*/
clear:both;
/*clear: both;意味着新增的子元素会清除左、右浮动元素,这里当然可以只使用left。*/
}
...
<section class="clearfix">
<img src="img/1.png"/>
<p>
jQuery is a fast.
</p>
</section>
总结
三种方法因地制宜。方法三的第二种方式使用广泛。