Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS margin overlap instead of giving distance [duplicate]

Tags:

html

css

Lately I had problem with margins but I wasn't able to resolve it. My HTML looked like this:

<div class="info-box">Some text</div>
<div class="form">...</div>

CSS:

.info-box{
    border-radius: 5px;
    border: 1px solid red;
    margin-bottom: 20px;
}

.form{
    margin-top: 20px;
}

And problem was that margins overlapped each other instead of give 40px distance between two elements.

My question is: why? I found that adding to .info-box overflow:hidden fixed this but maybe there is better way?

like image 529
adi86 Avatar asked Feb 15 '13 09:02

adi86


People also ask

Why do margins overlap CSS?

In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. This is an interactive element! Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!

How do I fix the collapse margin in CSS?

How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.


1 Answers

Again - you have to understand in what way margins are interpreted. Margin refers to another's element position not including its margins. You cannot sum margins.

How margins work

like image 183
kamil-mrzyglod Avatar answered Sep 25 '22 11:09

kamil-mrzyglod