【CSS】清除浮动

写三个盒子,如果没有浮动,三个盒子会自上而下排列;

如果三个盒子添加浮动,父元素(border:solid)不会随子元素盒子自适应。


三个盒子无浮动


添加浮动,父元素不自适应

清除浮动:

<div id="main">

<div id="box1"> </div>

<div id="box2"> </div>

<div id="box3"> </div>

</div>

方法一

新添加一个盒子,{clear:both}

<div id="box4"> </div>

<style type="text/css">

#main{ border: solid 1px; }

#box1{ width: 100px; height: 100px; background-color: #00FFFF; float: left; }

#box2{ width: 100px; height: 100px; background-color: #800080; float: left; }

#box3{ width: 100px; height: 100px; background-color: #FF0000; float: left; }

#box4{ clear: both; }

</style>


方法二:

父元素:overflow:hidden

<style type="text/css">

#main{ border: solid 1px; overflow: hidden; }

 #box1{ width: 100px; height: 100px; background-color: #00FFFF; float: left; }

#box2{ width: 100px; height: 100px; background-color: #800080; float: left; }

#box3{ width: 100px; height: 100px; background-color: #FF0000; float: left; }

</style>


方法三:添加伪类

  #main:after{ content: ""; clear: both; display: table; }

<style type="text/css">

#main{ border: solid 1px; }

#main:after{ content: ""; clear: both; display: table; }

#box1{ width: 100px; height: 100px; background-color: #00FFFF; float: left; }

#box2{ width: 100px; height: 100px; background-color: #800080; float: left; }

#box3{ width: 100px; height: 100px; background-color: #FF0000; float: left; }

</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容