元素總寬度 = width(content)+ padding + border + margin。
.example {
width: 200px;
padding: 10px;
border: 5px solid #000;
margin: 20px;
}
/* 總寬度 = 200 + 20 + 10 + 40 = 270px */
width 包含 padding 與 border,總寬度 = width + margin(上例為 240px)。
設定 box-sizing: border-box 後,width/height 即為邊框盒尺寸,與舊 IE 行為一致,開發更直覺。
*, *::before, *::after {
box-sizing: border-box;
-moz-box-sizing: border-box; /* 旧版 Firefox */
-webkit-box-sizing: border-box; /* 旧版 Chrome/Safari */
}
position: absolute / fixedfloat: left/right這類元素若未設定寬度,會依內容自適應(shrink-to-fit),不佔據正常流空間。
CSS3 引入 display: flex(舊語法 display: box),提供更強大的佈局能力:flex-direction、justify-content、align-items、flex-grow 等屬性可輕鬆實現等高、置中、比例分配等效果。