--- tags: CSS, 六角筆記王 title: CSS - box-model --- # 容器大小怎麼變來變去的,到底誰影響了 box-model ? 使用區塊或行內元素時,是不是覺得元素的整體寬高不太一樣,又或是只知道加上 `box-sizing: border-box` 就萬無一失? 透過簡單的範例,快速理解 box-model。 ## box-model 每個元素都是 box-model,可以在網頁上按下右鍵進入開發者模式,接著在導覽列中點選頁籤 `Elements`,最後在右方區塊點選頁籤 `Styles` 並拉到最下方,這個就是 box-model。  它可以區分成四個部分,分別是 : | 對象 | 意義 | 說明 | | -------- | -------- | -------- | | content | 元素內容 | 像是文字或者區塊中的行內元素等等,在上圖中是顯示內容寬高 | | padding | 內距 | 邊框到內容的距離 | | border| 邊框 | 可以設定粗細大小、顏色、樣式 | | margin | 外距 | 元素與父層或同級的距離 | ## 使用情境 例如業務會手寫賀卡給客戶,將它們一一排好就是外距,寫文字在裡面並與卡片邊邊有距離就是內距,為了裝飾會畫個邊框,當然現實卡片邊邊無法加上粗細,有發現了嗎? 其實這張現實卡片就是 `box-sizing: border-box`。 每個元素的 `box-sizing` 預設為 `content-box`,若變更內距或者加上邊框,整體寬高就會被改變,但改為 `border-box`,無論內距與邊框怎麼改變距離與粗細,都不會影響整體寬高。但文字除外,文字無論是否超過容器大小,都不會影響整體容器寬高。而在 BootStrap 的 CSS 中也會看到這段, ```sass * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } ``` 這樣設定後,就不用特地再去每個元素算要調整多少內距或邊框粗細才能符合設計稿件元素大小。 ## 參考來源 > 1. [深入理解 CSS Box Model ( 盒子模型 )](https://www.oxxostudio.tw/articles/202008/css-box-model.html)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.