0

Link to the website: https://jsfiddle.net/L84vhah9/

Now go into the CSS, go all the way down to .box and change the margin: 0 auto; to margin: 2% auto;

Then check the website again. See how the whole section moves/gets the margin instead of just the box. It creates a space between the nav and section.

Why is this happening?

Shouldn't just the .box get the margin? I don't understand why <section> gets it.

Lal
  • 14,505
  • 4
  • 39
  • 63
  • I think you're misunderstanding what `margin` does. If you imagine your box element, margin will give it space outside of its border, and padding will give it space inside its border. There are some more well-put explanations here: http://stackoverflow.com/questions/2189452/when-to-use-margin-vs-padding-in-css – Lucas Watson Apr 30 '16 at 14:35
  • 1
    @Lucas I understand what margin and padding does. You might've missunderstood my problem. I want to add space on the top and bottom sides of the box, but when I did that it behaved like the section got the margin which created a space between the nav and the section with the section being the white space that the green boxes were inside. –  Apr 30 '16 at 14:40

1 Answers1

0

See this fiddle

You could easily solve the problem by adding

overflow:auto;

or

overflow: hidden;

to the parent div..ie to your section.

Thus, the updated CSS for section and .box would be as follows

section {
    overflow: hidden;
  width: 90%;
  height: auto;
  margin: 0 auto;
  background-color: #fff;
}

.box {
  width: 90%;
  height: 300px;
  margin: 2% auto;
  border: 5px solid #36FF54;
  background: #ffffff;
}
Lal
  • 14,505
  • 4
  • 39
  • 63
  • Thanks a lot! This was the only thing needed. Could you explain why it was behaving like it did before without overflow? –  Apr 30 '16 at 14:39
  • Great.. :) Glad that it helped you.. Actually, earlier I too had the same problem and while searching stack overflow I heard somebody saying that it is because the parent div fails to consider the height of the child div for some reason and hence that behaviour.. – Lal Apr 30 '16 at 14:42
  • Okay, makes a bit more sense now but I am still kinda lost. Thanks a lot anyway! Finally fixed it. :) –  Apr 30 '16 at 14:46
  • Happy to help.. :)... @Fotan could you please mark the answer as accepted if it really helped you.. – Lal Apr 30 '16 at 14:46
  • 1
    http://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element – Roko C. Buljan Apr 30 '16 at 14:51
  • @Lal Ok, No worries! :D –  Apr 30 '16 at 14:51
  • 1
    Better to use a proper `.clearfix` than `overflow:hidden` or **better/rather** `overflow:auto`. – Roko C. Buljan Apr 30 '16 at 14:52
  • understood @RokoC.Buljan..Thankyou for that info.. – Lal Apr 30 '16 at 14:53