.clearfix:before{ content:""; display: table;
}解决margin-top塌陷
2.浮动子元素动态改变父元素宽度:在设计网页布局时,为了便于快速布局,会将子元素设为浮动元素,父元素宽度设为固定,高度不设置,这样随着子元素的添加,父元素的高度就会动态变化,但尴尬的是,浮动子元素并不能"撑开父元素的高度",于是为父元素增加伪类便成了解决这种尴尬局面最好的方式;margin-top塌陷 body, a, p{ margin:0; padding:0; } .outside{ width:300px; height: 400px; background-color: green; margin: 0 auto; } .inside{ width: 50px; height:50px; background-color: gold; margin-top: 50px; } .clearfix:before{ content:""; display: table; }
.clearfix:after{ content: ""; display: table; clear:both;
}子元素动态改变父元素尺寸
小结:浮动子元素宽度 .outside{ width: 200px; border: 2px solid red; } .inside{ float: left; width: 200px; height: 100px; margin: 20px 0 20px; border: 1px solid green; } .clearfix:after{ content: ""; display: table; clear:both; }
以上两种情况极其常见,解决方式也很类似,所以可对两种方式做一个封装:
.clearfix:before, .clearfix:after{ content: ""; display: table;
}.clearfix:after{ clear:both;
}.clearfix{ zoom:1;
}以后遇到上面两种问题,只要将 小结 中的源码引入到对应的css(层叠样式表),最后在父元素class属性中 中引入clearfix即可
reset.css
h1,h2,h3,h4,h5,h6,p,body,ul,ol,dl,dd,dt,input{
margin: 0; padding: 0;
}ul,ol{
list-style: none;
}a{
text-decoration: none;
}em,i{
font-style: normal;
}b,strong{
font-weight: normal;
}.clearfix:before,.clearfix:after{ content: ""; display: table;
}.clearfix:after{ clear: both;
}.clearfix{
zoom:1;
}


