Sobes.tech
Middle

What is border collapsing in CSS?

sobes.tech AI

Answer from AI

Margin collapsing is a phenomenon in CSS where the vertical margins of two or more adjacent blocks combine into a single margin. The size of this combined margin is determined by the largest of the collapsing margins.

Main rules of collapsing:

  • Only vertical margins (margin-top and margin-bottom) collapse. Horizontal margins do not.
  • Margins of adjacent elements collapse only if there are no other elements, padding, borders, or block content between them.
  • The top margin of the first child collapses with the top margin of its parent if there is no padding, border, or other content between them.
  • The bottom margin of the last child collapses with the bottom margin of its parent if there is no padding, border, or other content between them.
  • The top and bottom margins of an empty element can collapse with each other if there is no padding, border, or content.
  • If one of the collapsing margins is negative, the resulting size is the sum of the positive and negative values (or the absolute value if both are negative and the total is less than zero).

Example:

<div class="box1">Element 1</div>
<div class="box2">Element 2</div>
.box1 {
  margin-bottom: 20px;
}

.box2 {
  margin-top: 30px;
}

In this case, the vertical distance between box1 and box2 will be 30px (the maximum of 20px and 30px), not 50px.

Ways to prevent collapsing:

  • Add padding or border between elements.
  • Create a new formatting block (for example, using overflow: hidden, display: flow-root, or floating elements).
  • Use display: inline-block, display: flex, or display: grid for the elements.
  • Use absolute positioning.