Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Last active March 4, 2022 04:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gokulkrishh/1c197d0369c45a8153d327b11d1626ca to your computer and use it in GitHub Desktop.
Save gokulkrishh/1c197d0369c45a8153d327b11d1626ca to your computer and use it in GitHub Desktop.
margin collapsing in css

There are two main types of margin collapse:

  • Collapsing margins between adjacent elements
  • Collapsing margins between parent and child elements

Using a padding or border will prevent collapse only when Collapsing is between parent and children. Also, any value of overflow different from its default (visible) applied to the parent will prevent collapse.

Thus, both overflow: auto and overflow: hidden will have the same effect.

To prevent Collapsing margins between adjacent elements

  • float: left / right
  • display: inline-block
  • position: absolute

Has both parent/child and ajadent sibilings collapsing

<div id="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>
#container {
    background: #ccc;
    width: 200px;
}
.square {
    margin: 10px;
    height: 50px;
    background: #f0f;
}

Fix parent/child collapsing

#container {
    background: #ccc;
    width: 200px;
    position: absolute; /* to prevent parent/child collpasing */
}
.square {
    margin: 10px;
    height: 50px;
    background: #f0f;
}

Fix parent/child collapsing and ajacent siblings collapsing

#container {
    background: #ccc;
    width: 200px;
}
.square {
    margin: 10px;
    height: 50px;
    background: #f0f;
    display: inline-block; /* to prevent adjacent collapsing */
    width: 180px;
}

For preview check below comments:

@gokulkrishh
Copy link
Author

Example 1: Screenshot 2020-05-04 at 11 22 42 AM

@gokulkrishh
Copy link
Author

Example 2:
Screenshot 2020-05-04 at 11 22 29 AM

@gokulkrishh
Copy link
Author

Example 3:
Screenshot 2020-05-04 at 11 22 20 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment