Width, height and box sizing
Definition and purpose
box-sizing determines which box a specified width or height sizes. With content-box the declared length targets content; with border-box it targets the border box.
Compare sizing modes
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> div { width: 200px; padding: 20px; border: 5px solid; } #a { box-sizing: content-box; } #b { box-sizing: border-box; } </style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>Both computed width strings are 200px, but outer sizes differ: 250px and 200px.
Syntax and mental model
For width: 200px, padding: 20px and border: 5px, content-box produces 250px outer border width; border-box produces 200px with 150px content. The content size cannot become negative. Margin is never included in box-sizing.
Percent width with padding
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #wrap { width: 200px; } #a { width: 100%; padding: 10px; box-sizing: border-box; } </style> </head> <body> <section id="wrap"> <div id="a">Panel</div> </section> </body></html>A fills its parent without adding padding beyond the declared width.
Common mistakes
A fixed height can clip content when text grows. Prefer automatic height for text panels and inspect the actual box edges rather than assuming width includes margins.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Box edges and spacing. Next lesson: Minimum and maximum sizes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Width, height and box sizing — knowledge check
Five questions on width, height and box sizing.
What does content-box size?
With 200px border-box width, 20px padding and 5px borders, what is content width?
Does border-box include margin?
Why avoid fixed heights for text?
If padding plus borders exceed a border-box width, can content width become negative?