兩端對齊效果
如上圖中紅色的9個div它們中間有間距,而最左邊和最右邊是沒有間距的,這種布局如果使用css3的flex來實現是非常簡單的,而如果要使用float布局就需要一些特殊的技巧了。
實現原理
紅色的9個div左浮動,左右margin為25px,父容器左右margin為-25px,這樣相當于是把父容器拉長了,因此就達到了兩端對齊的效果。Bootstrap的柵格系統就是這么干的,bootstrap要求我們.col-xx-xx的父容器需要為.row,而.row的左右padding就為-15px。
示例代碼
<style type="text/css">*{margin: 0;padding: 0;}.container{ width: 1300px; margin: 0 auto; background-color: #f90;}.header{ width: 1000px; height: 40px; margin: 0 auto; background-color: #eee;}.main{ width: 1000px; margin: 0px auto; background-color: #f60;} .box{ /*給.box設置左右margin為負的就是為了沖突掉最左邊元素的margin-left和最右邊元素的margin-right*/ margin: 0 -1.6666667%;}.box::after,.box::before{display: table;content: " ";}.box::after{clear: both;}.item{ width: 30%; height: 200px; margin: 20px 1.6666667%; background-color: #f10; float: left;}</style>
<div class="container"><div class="header">下面的元素會與我對齊</div> <div class="main"> <div class="box"> <div class="item">我是第1個div元素</div> <div class="item">我是第2個div元素</div> <div class="item">我是第3個div元素</div> <div class="item">我是第1個div元素</div> <div class="item">我是第2個div元素</div> <div class="item">我是第3個div元素</div> </div> </div></div>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答