當我們需要讓容器內的幾個子元素平均排布時,可以借助浮動與百分比寬度來實現。以「性別」單選按鈕為例:
<div style="width: 62%;margin: auto;">
<div style="float:left;width: 49%; text-align: center">
<input type="radio" checked="checked"/>男
</div>
<div style="float:left;width: 49%; text-align: center">
<input type="radio"/>女
</div>
</div>
原理很簡單:把內部每個 DIV 向左浮動,並將寬度設為略小於平均值(這裡取 49% 而非 50%,是為了防止因四捨五入或邊距把容器擠爆而換行),子元素便能均匀分布。
小提醒:採用這種浮動方式後,如果下方還緊接著其他元素,記得在後續元素的樣式中加上:
clear: both;
這樣可以清除浮動影響,避免下面的元素布局被帶動錯位。