Performance: Box sizing
Box sizing affects how the browser calculates element sizes, impacting layout stability and rendering speed.
Jump into concepts and practice - no test required
div {
width: 200px;
padding: 20px;
box-sizing: border-box;
}div {
width: 200px;
padding: 20px;
box-sizing: content-box;
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| content-box with padding | Normal DOM nodes | Multiple reflows if padding changes | Higher paint cost due to layout shifts | [X] Bad |
| border-box with padding | Normal DOM nodes | Single reflow on size change | Lower paint cost, stable layout | [OK] Good |
box-sizing: border-box; do?content-box model adds padding and border outside the width and height, while border-box includes them inside.border-boxbox-sizing: border-box; means the total size includes padding and border, making layout easier.content-box and border-box. Others like padding-box or size-box are invalid.border-box includes padding and border inside the element's size.div {
width: 200px;
padding: 20px;
border: 10px solid black;
box-sizing: content-box;
}
What is the total width of the div element as rendered in the browser?content-box, width is content only. Padding and border add outside width.p {
width: 150px;
padding: 15px;
border: 5px solid blue;
box-sizing: border-box;
}
But the paragraph is wider than 150px on the page. What is the likely cause?border-box, padding and border are inside the width, so total width should be 150px.box-sizing: border-box;.button {
width: 300px;
padding: 20px;
border: 5px solid black;
box-sizing: content-box;
} uses content-box, so total width > 300px.button {
width: 300px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
} uses border-box with 300px width, so total size is 300px.button {
width: 270px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
} sets width 270px with border-box, making total smaller than 300px.button {
width: 300px;
padding: 0;
border: 0;
box-sizing: border-box;
} removes padding and border, which is not desired.