Margin vs padding: where does the space go?
Understand inside and outside spacing in the CSS box model, with a small example you can change in the browser.
A card can feel cramped even when it has plenty of space around it. The difference is where that space lives. Padding creates room between the content and its border. Margin creates space beyond the border.
Think from the content outward
Picture four layers: content, padding, border, margin. A background color fills the content and padding areas. The margin stays outside the element’s painted box.
.card {
box-sizing: border-box;
width: 260px;
max-width: 100%;
padding: 24px;
border: 2px solid #526d14;
margin: 32px 0;
background: #d4ef78;
}What changes when you edit the values?
Increase padding to 40px: the text has more room inside the card’s border. Increase the vertical margin to 48px: the card moves farther from surrounding content. With border-box, its declared width still includes padding and border.
Use gap for space between layout items
In a flex or grid container, gap is often a clearer way to separate sibling items. It adds gutters between the items without requiring an extra margin on the last item. Padding can still give the entire container room around its contents.
A detail to watch: vertical margin collapse
Some vertical margins in normal block layout can collapse together. This means adding two adjacent margins does not always produce their sum. Flex and grid layouts do not collapse their items’ margins in this way.
Open the box-model lesson. Change padding and margin one at a time. Watch the border: it makes the difference between inside and outside spacing visible.
Further reference: MDN Web Docs ↗
Try the editable example ↗