Margins, Padding, and Borders
Prerequisites: The box model
Shorthands
margin and padding take one to four values, going clockwise from
the top:
.a { padding: 1rem; } /* all four sides */
.b { padding: 1rem 2rem; } /* top/bottom, left/right */
.c { padding: 1rem 2rem 3rem; } /* top, left/right, bottom */
.d { padding: 1rem 2rem 3rem 4rem; } /* top, right, bottom, left */
.e { margin-top: 0; padding-left: 1rem; }
Logical properties
margin-inline / padding-inline (the start and end of a line — left
and right in English) and margin-block / padding-block (top and
bottom) adapt to the text direction:
.card { padding-block: 1rem; padding-inline: 1.5rem; }
.icon { margin-inline-end: 0.5rem; }
In a right-to-left page, margin-inline-end becomes a left margin
automatically.
Centering a block
.container {
max-width: 60rem;
margin-inline: auto;
padding-inline: 1rem;
}
auto margins split the free space equally, centering a block that's
narrower than its container.
Borders
.card {
border: 1px solid #d0d0d0;
border-radius: 12px;
}
.tab { border-bottom: 3px solid transparent; }
.tab.active { border-bottom-color: navy; }
.avatar { border-radius: 50%; }
.note { border-left: 4px dashed orange; }
border = width, style (solid, dashed, dotted, double, none),
and color. Without a style, no border shows. border-radius: 50% on a
square makes a circle.
outline looks similar but takes no space and doesn't affect layout —
browsers use it for focus rings.
Margin collapsing
Vertical margins between block elements collapse: the gap is the larger of the two, not the sum:
<style>
.one { margin-bottom: 30px; height: 20px; }
.two { margin-top: 20px; height: 20px; }
</style>
<div class="one"></div>
<div class="two"></div>
<script>
const one = document.querySelector(".one").getBoundingClientRect();
const two = document.querySelector(".two").getBoundingClientRect();
console.log("gap:", two.top - one.bottom);
</script>
gap: 30
The gap is 30 pixels, not 50. Margins don't collapse inside flex and grid
containers, or horizontally. A child's top margin can also "leak" out
through a parent with no border or padding — a common surprise. Many
teams avoid it by using margins in one direction only (for example,
margin-block-end) or by using gap in flex and grid layouts.
Practice
Give .button 0.5rem of padding top and bottom and 1.25rem left and
right, a 2-pixel solid border in its text color, and fully rounded ends.
Show solution
.button {
padding: 0.5rem 1.25rem;
border: 2px solid currentColor;
border-radius: 999px;
}
A very large border-radius in pixels gives a "pill" shape whatever the
button's size.