The CSS Box Model
What is the Box Model?
Every HTML element is a rectangular box. The CSS box model describes how these boxes are sized and spaced. Understanding this is crucial for layout and positioning.
The Four Parts
The box model consists of four areas, from inside to outside:
- Content - The actual content (text, images, etc.)
- Padding - Space between content and border
- Border - Line around the padding
- Margin - Space outside the border
Visualizing the Box Model
Let's see how padding, border, and margin create space around content.
Total Element Size
By default, the total width of an element is calculated as:
total width = width + padding-left + padding-right + border-left + border-right
Box-Sizing Property
The box-sizing property changes how width and height
are calculated. border-box includes padding and border
in the width, making sizing much easier.
box-sizing: border-box globally for easier,
more predictable layouts. Add this to your CSS reset:
* { box-sizing: border-box; }
Key Concepts
- Every element is a box with content, padding, border, and margin
- Default: width/height only applies to content area
box-sizing: border-boxincludes padding and border in width/height- Margin creates space between elements
- Padding creates space inside the element
Quick Quiz
Which box-sizing value includes padding and border in the element's width?
Enjoying these tutorials?