19

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?

squaleLis
  • 6,116
  • 2
  • 22
  • 30
adi86
  • 253
  • 1
  • 2
  • 8

1 Answers1

52

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

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29
  • 1
    Yes but why when I have added overflow: hidden to .info-box it worked? I assume that paddings can be summed? – adi86 Feb 15 '13 at 09:13
  • @user1785951 - I tried it with your suggestion and it didn't work for me :) Yes, paddings can be summed cause they are within block element - they refers to containing element, not siblings. But you have to remember they don't work as margins. – kamil-mrzyglod Feb 15 '13 at 09:18
  • Ok I get it know thanks a lot – adi86 Feb 15 '13 at 09:20
  • 11
    W3C specification indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero. Margin refers to another's element position not including its margins. You can sum padding but not sum margins. – Kurenai Kunai Apr 21 '15 at 07:28
  • 3
    Best answer so far. Even better than in the article marked as duplicate. – Vinz May 11 '15 at 14:30
  • If you have elements above that are inline then the margins will sum together with the bottom element. – ness-EE Dec 22 '15 at 18:17
  • Firstly, since "margin refers to another's element position not including its margins", why does it only apply _**vertically**_? Secondly, why doesn't it work the same way for _**inline**_ elements, in that margins are summed up? Just a little confused with the seemingly inconsistent implementation & wondered the justification behind it. – Giraldi Oct 26 '17 at 06:53
  • @Giraldi I believe some answers can be found in the specification https://www.w3.org/TR/CSS2/box.html#margin-properties – kamil-mrzyglod Oct 27 '17 at 17:09