CSS Box Model: Margin, Border and Padding
The CSS box model explains how the browser calculates the space an element occupies. Each box has content, padding, a border and a margin.
The four parts of a CSS box
- Content: Text, images or other page content.
- Padding: Space between content and the border.
- Border: The edge around padding and content.
- Margin: Space outside the border that separates neighboring elements.
Set box dimensions
.card {
width: 320px;
padding: 20px;
border: 2px solid #dce3eb;
margin: 16px;
}
With the default content-box sizing, width applies to the content. In this example the border-box width is 320 + 20 + 20 + 2 + 2 = 364 pixels. The 16-pixel margins add space outside that box, so two such cards also need room between and around them.
Use border-box for predictable sizing
*,
*::before,
*::after {
box-sizing: border-box;
}
With border-box, the declared width includes the content, padding and border. In the same example, the border-box stays 320 pixels wide and the content area becomes 276 pixels. Margins remain outside the declared width.
Use margin and padding shorthand
One value applies to all four sides. With two values, the first sets the top and bottom while the second sets the left and right:
.card {
margin: 12px 20px;
padding: 1rem 1.5rem;
}
For a fixed or maximum width, margin-inline: auto can center a block in its available space:
.page-content {
width: min(100% - 2rem, 70rem);
margin-inline: auto;
}
Understand vertical margin collapse
When the vertical margins of adjacent block elements meet, they can collapse into one margin instead of adding together. For example, a 24-pixel bottom margin next to a 16-pixel top margin usually leaves 24 pixels between the blocks, not 40. This behavior applies to vertical margins; horizontal margins do not collapse. Margins between flex or grid items do not collapse either.