You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The CSS box model is the foundation of layout on the web. Every HTML element is rendered as a rectangular box, and the box model describes how the size of that box is calculated. Understanding the box model is essential for controlling spacing, sizing, and alignment.
Every element's box consists of four layers, from inside to outside:
┌──────────────────────────────────┐
│ Margin │
│ ┌────────────────────────────┐ │
│ │ Border │ │
│ │ ┌──────────────────────┐ │ │
│ │ │ Padding │ │ │
│ │ │ ┌────────────────┐ │ │ │
│ │ │ │ Content │ │ │ │
│ │ │ └────────────────┘ │ │ │
│ │ └──────────────────────┘ │ │
│ └────────────────────────────┘ │
└──────────────────────────────────┘
| Layer | Description | CSS Property |
|---|---|---|
| Content | The actual text, image, or child elements | width, height |
| Padding | Space between the content and the border | padding |
| Border | A line around the padding | border |
| Margin | Space outside the border, separating the element from others | margin |
The content area is where your text and child elements live:
.box {
width: 300px;
height: 200px;
}
Important: By default (
box-sizing: content-box),widthandheightset the size of the content area only. Padding and border are added on top of the specified width, making the total box larger than expected.
Padding creates space inside the element, between the content and the border:
.box {
/* All four sides */
padding: 20px;
/* Vertical | Horizontal */
padding: 10px 20px;
/* Top | Horizontal | Bottom */
padding: 10px 20px 30px;
/* Top | Right | Bottom | Left (clockwise) */
padding: 10px 20px 30px 40px;
}
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
The border sits between the padding and the margin:
.box {
/* Shorthand: width style colour */
border: 2px solid #333;
/* Individual properties */
border-width: 2px;
border-style: solid;
border-color: #333;
/* Rounded corners */
border-radius: 8px;
}
| Style | Appearance |
|---|---|
solid | A solid line |
dashed | A dashed line |
dotted | A dotted line |
double | A double line |
none | No border |
hidden | Like none, but takes precedence in table borders |
.box {
border-top: 3px solid navy;
border-bottom: 1px dashed #ccc;
border-left: none;
border-right: none;
}
.box {
border-radius: 8px; /* All corners */
border-radius: 50%; /* Circle (if width = height) */
border-radius: 8px 0 0 8px; /* Top-left, top-right, bottom-right, bottom-left */
}
Margin creates space outside the element, separating it from other elements:
.box {
/* All four sides */
margin: 20px;
/* Vertical | Horizontal */
margin: 20px auto; /* auto centres the element horizontally */
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.