Measure all four layers of a box
A box has a content area, padding around that content, a border around the padding, and margin outside the border. Understanding which layer you change makes spacing predictable. Backgrounds normally paint behind content and padding; margins remain outside the box's painted area.
.card {
width: 240px;
padding: 20px;
border: 2px solid #2563eb;
margin: 16px;
background: #eff6ff;
}With the default content-box sizing, the border-box width is 240+40+4 = 284px. Including both horizontal margins, its horizontal outer extent is 316px in this simple calculation. Margin collapsing can affect vertical relationships, so do not generalize every vertical measurement as a simple sum.
Spacing shorthand
.example {
padding: 8px 16px 12px 20px;
margin: 1rem 2rem;
}Four values follow top, right, bottom, left. Two values mean vertical then horizontal. Logical properties such as padding-inline and margin-block express spacing relative to the writing direction and can support multilingual layouts more naturally.
Separate internal and external spacing
Use padding to keep a card's text away from its own border. Use a parent layout's gap or deliberate margins to separate neighboring cards. Adding many unrelated margins to children often makes a layout harder to maintain than one parent gap rule.
Height and overflow
A fixed height can clip text when users zoom or content grows. Prefer natural height with padding, or min-height when a minimum is required. Overflow is a symptom to investigate, not always a reason to hide content.
Practice with developer tools
- Inspect a card's box-model diagram and identify each measurement.
- Set padding to zero, then margin to zero, observing different effects.
- Compute the border-box width for width 200px, 12px padding and 1px borders. Answer: 226px under content-box.
- Add a long paragraph and zoom to 200%; confirm the box grows rather than covering adjacent content.
हिन्दी संकेत: padding अंदर की दूरी है, margin बाहर की। Width की गणना box-sizing पर निर्भर है।