#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 6 of 49medium

What is Margin Collapse?

Understanding when and why margins collapse in CSS.

What You'll Learn

  • What margin collapse is
  • When it happens
  • How to prevent it

What is Margin Collapse?

When vertical margins of adjacent elements touch, they collapse into a single margin equal to the larger of the two.

When It Happens

  • Adjacent siblings
  • Parent and first/last child
  • Empty blocks

Example

styles.cssCSS
/* Both have 20px margin, but gap is 20px not 40px */
.box1 { margin-bottom: 20px; }
.box2 { margin-top: 20px; }

How to Prevent

styles.cssCSS
/* Add padding or border to parent */
.parent {
  padding-top: 1px;
}

/* Use flexbox or grid */
.parent {
  display: flex;
  flex-direction: column;
}

/* Use gap instead of margin */
.parent {
  display: flex;
  gap: 20px;
}