CSS Box Model
The CSS Box Model describes how every HTML element is treated as a rectangular box.
It has 4 parts:
┌───────────────────────────────┐ │ MARGIN │ │ ┌─────────────────────────┐ │ │ │ BORDER │ │ │ │ ┌───────────────────┐ │ │ │ │ │ PADDING │ │ │ │ │ │ ┌─────────────┐ │ │ │ │ │ │ │ CONTENT │ │ │ │ │ │ │ └─────────────┘ │ │ │ │ │ └───────────────────┘ │ │ │ └─────────────────────────┘ │ └───────────────────────────────┘
1. Content
The actual text, image, or other content inside the element.
.box { width: 300px; height: 200px; }
2. Padding
Space inside the element, between the content and border.
.box { padding: 20px; }
3. Border
A line surrounding the padding and content.
.box { border: 2px solid black; }
4. Margin
Space outside the element, separating it from other elements.
.box { margin: 30px; }
Complete Example
.box { width: 300px; height: 200px; padding: 20px; border: 5px solid black; margin: 30px; }
With the default box-sizing: content-box, the actual width is:
Content width = 300px Padding = 20px + 20px Border = 5px + 5px Total width = 350px
Box-Sizing
A very useful property is:
* { box-sizing: border-box; }
With border-box, the specified width includes content + padding + border.
For example:
.box { width: 300px; padding: 20px; border: 5px solid black; box-sizing: border-box; }
Now the total width remains 300px.
Easy way to remember
Content → Padding → Border → Margin
CONTENT ↓ PADDING ↓ BORDER ↓ MARGIN
padding = space inside
margin = space outside
Comments
Post a Comment