在其他博客上看到了一片关于父容器高度自动变化的博文,发现自己也不是全都知道,学习后分享给大家;
原来一直设置父元素高度为auto,但发现效果并不对,一直以来都没有思考这个问题;
想要设置父元素高度随着子元素自动变化,有以下几种方式可以参考:
1.清除浮动
<style type="text/css">
.child{
width: 100px;
height: 100px;
background: pink;
float: left;
}
.parent{
width: 100%;
height: auto;
background: blue;
}
</style>
<div class='parent'>
<div class='child'>父元素</div>
<div class='child'>父元素</div>
<div style="clear: both;display: block"></div>
</div>
2.增加一个子元素,但页面上不显示
<div class='parent'>
<div class='child'>子元素</div>
<div class='child'>子元素</div>
<div style="height:1px; margin-top:-1px;clear: both;overflow:hidden;"></div>
</div>