CSS基础之清除浮动
CSS基础之清除浮动
本人前端菜鸟一枚,在学习 CSS 过程中发现网上流传的教程参差不齐,要么内容不够详细,要么方法就是错的。本文是在我参考了许多前辈经验的基础上编写的,如有错误的地方,请各位大牛不吝赐教。以下是我总结的三种行之有效而且比较简单实用的方法。
一、父级div定义伪类 :after
代码如下:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>CSS基础之清除浮动</title><style>*{margin:0;padding:0;}#header,#footer{width:100%;height:50px;background:#3ac;}.father{margin:10pxauto;}.float_left{float:left;background:#a3f;width:70%;height:450px;}.float_right{float:right;background:#f3f;width:30%;height:300px;}.father:after{display:block;content:"";clear:both;}</style></head><body><divid="header">头部</div><divclass="father"><divclass="float_left">left</div><divclass="float_right">right</div></div><divid="footer">底部</div></body></html>
其中关键的部分为:
.father:after{display:block;content:"";clear:both;}
这里 content 的值尽量写为空或者不写,如果写其他值,则需添加多余的代码,举例如下:
.father:after{display:block;height:0;visibility:hidden;content:"清除浮动";clear:both;}
虽然也能清除浮动,但多了一些不必要的代码。
二、在结尾处添加空的div标签
原理跟使用 :after 伪类一样,都是通过clear: both; 来实现的。示例代码如下
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>CSS基础之清除浮动</title><style>*{margin:0;padding:0;}#header,#footer{width:100%;height:50px;background:#3ac;}.father{margin:10pxauto;}.float_left{float:left;background:#a3f;width:70%;height:450px;}.float_right{float:right;background:#f3f;width:30%;height:300px;}.clr{display:block;content:"";clear:both;}</style></head><body><divid="header">头部</div><divclass="father"><divclass="float_left">left</div><divclass="float_right">right</div><divclass="clr"></div></div><divid="footer">底部</div></body></html>
三、父元素定义 overflow:auto;
HTML结构跟上面一样,CSS样式部分如下:
*{margin:0;padding:0;}#header,#footer{width:100%;height:50px;background:#3ac;}.father{margin:10pxauto;overflow:auto;}.float_left{float:left;background:#a3f;width:70%;height:450px;}.float_right{float:right;background:#f3f;width:30%;height:300px;}
这种方法使用起来很简单,但具有一定的局限性。内部宽高超过父级div时,会出现滚动条。
以上就是清除浮动的三种方法。另外如果父元素本身也是浮动的话,则父元素内就无需清除浮动。要根据实际情况选择可行的方法。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。