Try   HackMD

CSS|box-sizing|position:fixed|解決 width:100% 右邊 padding 內的物件超出容器

Alert Message Box 提示訊息框,預期狀態如下圖:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

問題描述:

當我在製作 Alert Message 時,想讓該元件固定於網頁底部,同時左右滿版適應到裝置大小,直覺先設定 width: 100% 然後使用 position:fixed 將此元件固定位置。

但當增加 padding 後,float:right 的按鈕"X"就會消失。

 
HTML 部分架構

<div class="alert">
   <span class="closebtn">&times;</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")

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

 

​.alert {
​    position: fixed;
​    padding: 20px;
​    width: 100%;
​    left: 0;
​    bottom: 0;
​    background-color: #7E5E4C;
​    color: #FCE3AB;
​    text-align:center;
​  } 

加入 padding 後預覽如下:(此時右邊 close button "X" 就消失了)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

 

但我們於 chrome 中檢查,padding 是正常作用的

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

為什麼會這樣呢?

研究過後發現原因是出在兩個部分:

  • position
  • width

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)

 

有以下兩種解法:

  1. 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;
   } 
  1. 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 是比較好的方法,比較容易閱讀理解,維護性更高。


參考資料:


tags: CSS