我们在使用float浮动进行布局的时候知道一般需要给浮动的块元素加上一个父级元素,这样元素浮动时才可以在父元素内部按照我们需要的方式进行布局,但是有一个问题是如果父元素没有给定高度的话当内部元素进行浮动之后父元素的高度就会是0,这是因为浮动的元素是处于标准流之外的。若是在一开始给定父元素一个高度的话很多时候也不能满足要求,因为很多我们不知道要显示的内容具体是多少,所以也就不知道需要给多少高度合适。
对于该问题的解决方式有三种:
额外标签法
在父元素内部浮动元素后面加上一个块级元素,一般是使用div,给该div一个clear属性为both即可。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.header{
width: 300px;
background-color: #fff;
}
.one {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.two {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.footer {
width: 100px;
height: 100px;
background-color: gray;
}
.clear {
clear: both; //添加了这个样式之后父元素虽然没有给定高度,但是依然会根据浮动的子
//元素的高度来自动撑开
}
</style>
</head>
<body>
<div class="header">
<div class="one">one</div>
<div class="two">two</div>
//该元素用于解决子元素浮动后父元素的高度为零的情形,注意上面的clear样式
<div class="clear"></div>
</div>
<div class="footer">footer</div>
</body>
</html>
上面这种方式确实可以解决问题,不过是通过添加无用的div块来解决问题,所以这种方式不太推荐。
overflow法
第二种方式是在父元素中加上一个样式 overflow:hidden
依然是上面的例子,该做法只是需要给父元素添加一个样式
.header{
width: 300px;
background-color: #fff;
overflow: hidden; //只需要在父元素的样式中加上这个即可
}
通过after伪元素解决
第三种方式是可以通过after伪元素来解决,这种方式的样式依然是将样式添加在父元素中。
依然是上面的案例,所不同的只是在父元素中添加了一个clearFix类而已,而清楚浮动的样式可以说是固定的写法,就是使用.clearFix:after{},这里面就是使用到了after伪元素
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.clearFix:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearFix {
*zoom: 1;
}
.header{
width: 300px;
background-color: #fff;
overflow: hidden;
}
.one {
width: 100px;
height: 100px;
background-color: red;
float: left;
}
.two {
width: 100px;
height: 100px;
background-color: green;
float: left;
}
.footer {
width: 100px;
height: 100px;
background-color: gray;
}
</style>
</head>
<body>
<div class="header clearFix">
<div class="one">one</div>
<div class="two">two</div>
</div>
<div class="footer">footer</div>
</body>
</html>
至于后面还写了.clearFix{*zoom:1}是因为ie浏览器不能识别after伪元素,所以这部分代码是为了兼容ie浏览器而写的,至于zoom前面的星号是一种标识,也就是说 * 号后面的内容只会在在ie浏览器中会执行,其他的浏览器是不能识别 * 好后面的内容的。