My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

CSS – Preventing Margin Collapse

At times the top and bottom margins of block elements might collapse into a single margin. Here are easy CSS solutions to prevent the margins of your block elements from collapsing.

One of the strange quirks you might face when coding in css, is that sometimes you can’t add any white space (margin) to some elements. In other words, no matter how much you increase the values of margins no white space will be show up in the browser. it’s a frustrating.

For instance, if you have two boxes and each of them have been given 20px margin, since top margin of the second box is in contact with the bottom margin of the first box, the margins collapse and the element will have a total margin of 20px rather than 40px.css margin

Margin collapse might also occur when one block element is the child of another block element. Again, the top and bottom margins of the second element disappears and there’s only 20px margin around parent element.

css margin 2

There are a couple of methods to prevent css Margin Collapse problem.

1-   Add a border to the element

2-   Add 1px of padding

3-   change the position property. Margins of absolutely and relatively positioned boxes don’t collapse.

Now they look ok:

css margin 3css margin 4

4 comments

Have your say