The Box Model
Understanding margins, padding, borders, and content sizing
The CSS Box Model
Every HTML element is a rectangular box. The box model defines how the size of that box is calculated.
The Four Layers
From inside out:
- Content - The actual text, image, or child elements
- Padding - Space between content and the border
- Border - The visible edge of the element
- Margin - Space outside the border, separating elements
.box {
width: 300px;
padding: 20px;
border: 2px solid #333;
margin: 16px;
}
CSSBox Sizing
By default, width only sets the content width. Padding and border are added on top:
Total width = width + padding-left + padding-right + border-left + border-right
= 300 + 20 + 20 + 2 + 2
= 344px (not what you expected!)Fix this with box-sizing: border-box:
*, *::before, *::after {
box-sizing: border-box;
}
CSSNow width: 300px means the total box is 300px, including padding and border.
Padding
Space inside the border:
/* All sides */
padding: 20px;
/* Vertical | Horizontal */
padding: 10px 20px;
/* Top | Right | Bottom | Left (clockwise) */
padding: 10px 20px 15px 20px;
/* Individual sides */
padding-top: 10px;
padding-right: 20px;
padding-bottom: 15px;
padding-left: 20px;
CSSMargin
Space outside the border:
/* Center a block element horizontally */
.container {
max-width: 1200px;
margin: 0 auto;
}
/* Spacing between elements */
p {
margin-bottom: 1rem;
}
CSSMargin Collapse
Vertical margins between adjacent elements collapse - only the larger margin is used:
h2 { margin-bottom: 20px; }
p { margin-top: 16px; }
/* Actual space between h2 and p = 20px (not 36px) */
CSSBorder
/* Shorthand: width style color */
border: 2px solid #333;
/* Individual properties */
border-width: 2px;
border-style: solid; /* solid, dashed, dotted, double, none */
border-color: #333;
/* Individual sides */
border-bottom: 1px solid #eee;
border-left: 4px solid blue;
/* Rounded corners */
border-radius: 8px;
border-radius: 50%; /* Circle */
CSS