浮動布局和定位布局為css中布局的常用的兩種布局方式,而且兼容性會比較好。隨着flex的流行,以后會是主流,新的東西好用,兼容不太好。IE10以下不兼容flex布局。
float布局會脫離文檔流,對頁面的布局造成影響,比如造成父級的高度坍塌等問題。清除浮動后,便不會影響文檔流。下面介紹一下現在清除浮動的一些方式。
一、父級添加overflow: hidden;
子元素浮動了,會造成父元素的高度坍塌。只要給父元素添加overflow: hidden;屬性,就可以解決浮動帶來的影響。
<ul class="cc"> <li></li> <li></li> </ul> <style type="text/css"> li { list-style: none; height: 100px; width: 100px; float: left; background: red; margin-left: 20px; } ul { overflow: hidden; padding: 0; margin: 0; background: pink; } </style>
二、通過屬性clear:both;達到清除浮動的目的;
元素浮動后,只需要在浮動元素添加多一個塊級元素,並添加clear: both;屬性,便可以達到清除浮動的目的。
<style type="text/css"> li { list-style: none; height: 100px; width: 100px; float: left; background: red; margin-left: 20px; } ul{ background: pink; } </style> <ul class="cc"> <li></li> <li></li> <div style="clear: both;"></div> </ul>
三、通過給父級元素添加偽類after,達到清除浮動的目的;
這種方式也是使用clear: both;的方式達到效果,只是變相的使用了偽類after,使得頁面結構更簡潔,也是常用的清理浮動的方式。
<style type="text/css"> li { list-style: none; height: 100px; width: 100px; float: left; background: red; margin-left: 20px; } .cc:after { content: ''; height: 0; line-height: 0; display: block; visibility: hidden; clear: both; } ul{ background: pink; } </style> <ul class="cc"> <li></li> <li></li> </ul>
四、使用雙偽類;
此方式和三原理一樣,代碼更簡潔。
<style type="text/css"> li { list-style: none; height: 100px; width: 100px; float: left; background: red; margin-left: 20px; } .cc:after, .cc:before { content: ""; display: block; clear: both; } ul { background: pink; } </style> <ul class="cc"> <li></li> <li></li> </ul>