CSS實現多個小方塊兩端對齊
阿新 • • 發佈:2020-09-04
需求
直接上圖吧,要實現多個小方塊在大盒子裡的兩端對齊,大部分我們都是想到用flex佈局,簡單方便。
實現
上程式碼:
HTML:
<div class="container">
<div class="justify">
<i>1</i>
<i>2</i>
<i>3</i>
<i>4</i>
</div>
</div>
CSS:
* { margin: 0; padding: 0; } html,body { width: 100%; height: 100%; } .container { width: 80%; margin-left: 10%; height: 50px; border: 1px solid #ccc; }
以上用flex佈局實現已經基本上能夠滿足日常的需求,由於有些情況需要相容IE低版本,那麼我們使用兩端對齊text-align:justify的方式來實現:
.justify { text-align: justify; } .justify:after { content: ""; display: inline-block; width: 100%; } i { display: inline-block; width: 30px; height: 30px; background-color: #ccc; border-radius: 3px; margin: 0 4px; text-align: center; line-height: 30px; }
注意:
使用justify來兩端對齊需要注意在只有一行的情況下並不能實現兩端對齊,那麼我們需要使用偽元素來偽造出第二行,這樣來使第一行實現兩端對齊。
補充:
MDN中text-align