基础代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.father{
width: 1000px;
background: green;
}
.chlid1{
width: 100px;
height: 100px;
background: pink;
float: left;
}
.child2{
width: 100px;
height: 100px;
background: yellow;
float: left;
}
</style>
</head>
<body>
<div class="father">
<div class="chlid1">子元素一</div>
<div class="child2">子元素二</div>
</div>
<p>hello</p>
</body>
</html>
效果如下:
父元素的高度为0,解决方法如下:
1.额外标签法:
在最后一个浮动标签后,新加一个标签,给其设置clear:both;
优点:通俗易懂,方便
缺点:添加无意义标签,语义化差
不建议使用。
<div class="father">
<div class="chlid1">子元素一</div>
<div class="child2">子元素二</div>
<div style="clear: both"></div>
</div>
<p>hello</p>
2.父级添加overflow属性:
父元素添加overflow:hidden,
.father{
width: 1000px;
background: green;
overflow: hidden;
}
优点:代码简洁
缺点:内容增多的时候容易造成不会自动换行导致内容被隐藏掉,无法显示要溢出的元素
不推荐使用
3.使用after伪元素清除浮动
但是只添加上面这一条语句并没有作用,要添加content,display,height属性
:after 的意思是再.outer内部的最后加入为元素:after,
首先要显示伪元素,所以display:block,
然后为伪元素加入空内容,以便伪元素中不会有内容显示在页面中,所以, content:"";
其次,为使伪元素不影响页面布局,将伪元素高度设置为0,所以, height:0,
最后,要清除浮动,所以,clear:both。
.father{
zoom: 1;//解决浏览器兼容性问题
}
.father:after{
content:''
display:block;
height:0;
clear:both;
}
优点:符合闭合浮动思想,结构语义化正确
缺点:ie6-7不支持伪元素:after,使用zoom:1触发hasLayout.
推荐使用
4.给父元素添加高度
缺点:局限性太大,必须知道所有子元素的高度
5.从最底层到最外层都浮动
缺点:想想就好了…不现实