# CSS3 - box-sizing 語法 - 假設我們現在有一個 box: CSS: ``` .box { width: 50px; height: 50px; border: 10px solid blue; padding: 10px; background: #000; } ``` 來算算看這個 .box 的寬度是多少? ![](https://i.imgur.com/TGxEIUp.png) A: 50 + border(10+10) + padding(10+10) = 90px 但這樣計算是不是有點麻煩呢? 則可以運用接下來的語法: `box-sizing:border-box;` - 什麼是: box-sizing-border-box? 一般來說,CSS 會預設 box-sizing:content-box; 其作法就是: 會把 padding 、 border 等相加起來等於寬度。 如果使用 `box-sizing-border-box` 只要寬度設定為50px 則無論如何 box 都會是 50px,則會去自動扣除 padding 、 border - 練習 border-box: ``` /* 將 box 設定為: box-sizing: border-box; */ .box { box-sizing: border-box; width: 50px; height: 50px; border: 10px solid blue; padding: 10px; background: #000; } ``` 這邊就可以看出其差異: ![](https://i.imgur.com/TGxEIUp.png) ![](https://i.imgur.com/F23oj0L.png) 如果改成 `box-sizing: border-box;` 當寬度希望是: 50px; 則其餘屬性,CSS會自動扣除(也可以想像成設定) 想辦法讓你指定的物件變成: 50px ### 使 CSS 檔案完全吃到 border-box 語法: ``` *,*:before,*:after { box-sizing: border-box; } ``` ###### tags: `HTML、CSS`