CPCODELAB
CSS

Margin, Padding, Borders, and Border-Radius

9 min read

Shorthand and Longhand Syntax

Both margin and padding accept 1–4 values following a top-right-bottom-left (clockwise) order. border is shorthand for border-width, border-style, and border-color.

css
.card {
  /* 1 value — all four sides */
  padding: 1rem;

  /* 2 values — top+bottom, left+right */
  margin: 2rem auto;

  /* 4 values — top right bottom left */
  padding: 8px 16px 12px 16px;

  /* Border shorthand */
  border: 1px solid #e2e8f0;

  /* Rounded corners */
  border-radius: 12px;

  /* Individual corners */
  border-radius: 4px 4px 12px 12px;

  /* Individual sides */
  border-top: 4px solid #6366f1;
  border-bottom: none;
}

Margin Collapse

Vertical margins between block elements collapse into the larger of the two values. A margin-bottom: 24px on a paragraph followed by a margin-top: 16px on the next paragraph results in a gap of 24px, not 40px. Flexbox and Grid containers do not collapse margins.

Margin collapse only happens between block-level elements in normal flow. It does not happen in flex or grid containers, or between elements where one has padding, border, or overflow set.

Ready to test yourself?
Practice CSS— quiz & coding exercises