前幾天在公司修改一個css 多個按鈕居中問題,其實這樣的問題很多前端程序員都遇到過,舉個例子吧:
在一行中有三個按鈕或是兩個按鈕...個數不定,然后間距固定;然后就有很多人把所有按鈕放到一個div中,把div置為margin:10px auto(距上10像素,居中,然后又給了一個固定寬度,按鈕放在這個div中,這樣按鈕就不能具體居中了) ,也不通用如果按鈕減少到兩個 或一個怎么辦,
也有很多人用javascript 動態的算出寬度然后計算一大堆,並且很多時候比好用
錯誤代碼:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style type="text/css"> 7 .foot{width: 100%; height: 30px; border: 1px solid #d2d2d2;} 8 .foot .b{width:300px; margin: 3px auto;} 9 .foot .b .button{display: inline-block;line-height: 20px; background-color: #900; padding: 3px 5px; margin-left: 10px;} 10 </style> 11 </head> 12 <body> 13 <div class="foot"> 14 <div class="b"> 15 <a href="" class="button">提交</a> 16 <a href="" class="button">提交</a> 17 <a href="" class="button">提交</a> 18 </div> 19 </div> 20 </body> 21 </html>
后來修改如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .foot{width: 100%; height: 30px; border: 1px solid #d2d2d2; text-align: center;} .foot ul{display: inline; margin-left: -10px;} .foot ul li{display: inline-block; margin-left: 10px; line-height: 30px;} .foot ul li a{background-color: #900; color: #fff;line-height: 20px;padding: 3px 5px;} </style> </head> <body> <div class="foot"> <ul> <li><a href="" class="button">提交</a></li> <li><a href="" class="button">提交</a></li> <li><a href="" class="button">提交</a></li> <li><a href="" class="button">提交</a></li> </ul> </div> </div> </body> </html>
其實這些問題看上去很簡單,單還是有很多初學者不能實現,很多人也行用javascript實現,其實完全沒有必要
