为父元素添加overflow:hidden
html标签(以下都以此为准):
<div class="parent"> <div class="child> Hello World </div> </div> <footer>Whatever</footer> style写法: .parent{ border:1px solid red; overflow:hidden; } .child{ width:20px; height:20px; background:black; float:left; }
同时浮动父元素
父元素浮动后会收缩包裹子元素,所以根据需要设置父元素的宽度。
parent的浮动会强制使footer布局在parent旁边,因此要使用clear:left
进行清除: .parent{ float:left; width:100%; } footer{ clear:left; }
添加非浮动的清除元素
为父元素添加一个新类
.clearfix:after { content:"."; display:block; height:0; visibility:hidden; clear:both; } 如果要考虑兼容的话,可以在父元素下添加一个新的子元素并将样式写成<div class="parent clearfix"></div>
:clear:left;