margin — CSS Technical Interview Questions & Answers

Space outside an element's border.

margin

  • Space outside an element's border.
  • margin is space outside the border — between this box and the next. padding is space inside, between border and text. border sits in the middle of the box model.
  • .card { margin: 16px; padding: 12px; } Vertical margins can collapse (two 16px become 16, not 32). That’s a viva classic.
  • Trap: using padding when you meant gap between cards (margin or flex gap).

Technical Interview Tip: margin outside, padding inside. Draw the box.

Code Examples for margin

margin — working example

.card {
  margin-top: 1rem;
  margin-right: 1.5rem;
  margin-bottom: 1rem;
  margin-left: 1.5rem;
}

/* Shorthand: top/right/bottom/left */
.stack > * + * {
  margin: 0.75rem 0 0;
}

.center-block {
  width: 320px;
  margin-inline: auto; /* horizontal centering */
}

margin is space outside the border; vertical margins can collapse between siblings.

How to Explain margin to an Interviewer

margin vs padding?

margin outside the border padding inside