You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Every element in HTML is represented as a rectangular box. The CSS box model describes how that box is sized and spaced. Understanding the box model is fundamental to controlling layout in CSS.
Every element's box consists of four nested layers, from inside to outside:
.box {
/* Content size */
width: 300px;
height: 150px;
/* Padding (inside the border) */
padding: 20px;
/* Border */
border: 2px solid #333;
/* Margin (outside the border) */
margin: 30px;
}
By default, CSS uses content-box sizing: width and height set the size of the content area only. Padding and border are added on top, making elements larger than you expect.
The border-box model is almost always preferable: width and height include padding and border, so the element is exactly the size you set:
/* Apply to every element — the modern standard reset */
*,
*::before,
*::after {
box-sizing: border-box;
}
.card {
width: 300px; /* total width including padding and border */
padding: 20px;
border: 2px solid #ddd;
/* content area = 300 - 40 (padding) - 4 (border) = 256px */
}
Padding and margin accept shorthand:
/* All four sides equal */
padding: 20px;
/* Top/bottom | left/right */
padding: 10px 20px;
/* Top | left/right | bottom */
padding: 10px 20px 15px;
/* Top | right | bottom | left (clockwise) */
padding: 10px 20px 15px 5px;
The same shorthand applies to margin.
A surprising CSS behaviour: vertical margins collapse. When two block elements are stacked vertically, their margins do not add — the larger margin wins:
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }
/* The gap between h2 and p is 24px, not 40px */
Margin collapse only applies to vertical (top/bottom) margins between block-level elements. It does not happen with flex or grid children.
The display property controls how an element participates in layout:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.