CSS Box Model
Understand how every element in web design is a rectangular box with content, padding, border, and margin
What is the CSS Box Model?
Every element in web design is a rectangular box. The CSS box model describes how these boxes are sized and positioned.
The Box Model consists of four parts:
- Content - The actual content of the box (text, images, etc.)
- Padding - Clears an area around the content (inside the border)
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border (transparent space between elements)
Box Model in Action
Example Code
/* The CSS Box Model */ .element { /* Content */ width: 300px; height: 200px; /* Padding - space inside the border */ padding: 20px; /* All sides */ padding: 10px 20px; /* Top/Bottom, Left/Right */ padding: 10px 15px 20px 25px; /* Top, Right, Bottom, Left */ /* Border - line around the element */ border: 2px solid black; /* All sides */ border-top: 1px solid red; border-right: 3px dashed blue; border-bottom: 2px dotted green; border-left: 4px double orange; border-radius: 10px; /* Rounded corners */ /* Margin - space outside the border */ margin: 30px; /* All sides */ margin: 15px 30px; /* Top/Bottom, Left/Right */ margin: 10px 20px 30px 40px; /* Top, Right, Bottom, Left */ /* Box-sizing property */ box-sizing: content-box; /* Default - width/height only apply to content */ box-sizing: border-box; /* Width/height include padding and border */ }
content-box vs border-box
content-box (Default)
The width and height properties include only the content. Padding and border are added to the total size.
border-box
The width and height properties include content, padding, and border. The actual content size is calculated by subtracting padding and border from the specified width/height.
Tip: Many developers use box-sizing: border-box;
for all elements because it makes sizing more predictable. You can apply it globally with:
Margin Collapse
When two vertical margins meet, they collapse into a single margin. The size of the collapsed margin is equal to the larger of the two individual margins.
Vertical Margins Collapse
When two block elements are stacked vertically, the space between them will be the larger of their margins, not the sum.
Horizontal Margins Don't Collapse
When two inline or inline-block elements are placed side by side, their horizontal margins add up.
Practical Box Model Examples
Button Styling
Card Component
Card Title
This is an example card component using box model properties.