0

I am using two divs, one on top with no content or height and the other below it with some content or just height. I wish to put some space between them and instead of using margin-bottom alone on the first div or margin-top alone on the second div I am evenly sharing the space between both, i.e. half the space on the first div's margin-bottom and half the sapce on the second div's margin-top. For some reason only one of the two seem to apply and the other is ignored.

Check out this example

http://jsfiddle.net/hkgq22x8/

body {
    margin:0px;
}
.element1 {
    margin-bottom:10px;
}
.element2 {
    margin-top:10px;
    border:1px solid #000;
    height:30px;
}
<div class="parent">
    <div class="element1"></div>
    <div class="element2"></div>
</div>

try removing either margin-top on .element2 or margin-bottom on .element1, the space remains the same, but remove both and the space disappears.

Lordbalmon
  • 1,634
  • 1
  • 14
  • 31
  • Margins collapse into each other by default. Why are you using extra markup to create space? – isherwood Mar 17 '15 at 16:45
  • are you asking me why I am using margin on two different elements? Of course I can avoid it, but I just wish to know why this happens – Lordbalmon Mar 17 '15 at 16:45
  • 4
    That's why. https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing – isherwood Mar 17 '15 at 16:46
  • not quite, https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing says if there is no `border` but the example I've given has a border. (edit: also I tried adding border on both, yet the same result) – Lordbalmon Mar 17 '15 at 16:50
  • You're misinterpreting that statement. Margins *on the same element* collapse if there are no content or borders. – isherwood Mar 17 '15 at 17:01
  • Not exactly, checkout this link http://jsfiddle.net/hkgq22x8/1/ I've added a height for the first element as well and borders too.. yet the same result. – Lordbalmon Mar 17 '15 at 17:25
  • You're still not getting it. That statement refers to the height of a *single element*. Say you have a div with nothing in it, and margins of 10px. Its total height will be 10px. Without knowing what your ultimate goal was here, I have no further advice. – isherwood Mar 17 '15 at 17:32
  • 1
    I understand what you are explaining about the height but never mind, I really really appreciate your patience and your time thank you very much. Though I do not fully understand I certainly know more than I did before :) – Lordbalmon Mar 17 '15 at 17:38

0 Answers0