當我在製作 Alert Message 時,想讓該元件固定於網頁底部,同時左右滿版適應到裝置大小,直覺先設定 width: 100% 然後使用 position:fixed 將此元件固定位置。
但當增加 padding 後,float:right 的按鈕"X"就會消失。
HTML 部分架構
<div class="alert">
<span class="closebtn">×</span>
<strong>Alert Message Box</strong>
</div>
CSS 最外層的 alert 樣式,尚未加入 padding
.alert {
position: fixed;
width: 100%;
left: 0;
bottom: 0;
background-color: #7E5E4C;
color: #FCE3AB;
text-align:center;
}
預覽如下:(此時右邊依然還可以看見 close button "X")
.alert {
position: fixed;
padding: 20px;
width: 100%;
left: 0;
bottom: 0;
background-color: #7E5E4C;
color: #FCE3AB;
text-align:center;
}
加入 padding 後預覽如下:(此時右邊 close button "X" 就消失了)
但我們於 chrome 中檢查,padding 是正常作用的
研究過後發現原因是出在兩個部分:
position 預設的 box-sizing 為 content-box,其規則是 width of any border or padding will be added to the final rendered width.(參考資料出處)
所以其 width 計算方式:window width + left-padding + right-padding.
以上條件了解後,我們便知道是因為增設了 padding,所以"X"被定位移出了螢幕可視範圍。
(備註:按鈕"X" css樣式是使用 float: right)
有以下兩種解法:
- width: calc(100% - 20px);
.alert { position: fixed; padding: 20px; width: calc(100% - 20px); left: 0; bottom: 0; background-color: #7E5E4C; color: #FCE3AB; text-align:center; }
- box-sizing: border-box;
.alert { position: fixed; padding: 20px; box-sizing: border-box; width: 100%; left: 0; bottom: 0; background-color: #7E5E4C; color: #FCE3AB; text-align:center; }
border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements.(參考資料出處)
個人認為 box-sizing: border-box 是比較好的方法,比較容易閱讀理解,維護性更高。
參考資料:
CSS