1

Newbie question alert, please take a look at this example: http://codepen.io/cguo/pen/mVNgvG

The h1 element's margin-top is 60px. Even though the h1 element is inside the container div, the margin-top is not set relative to the container but to the top of the page.

To achieve what I want, I have to change h1's margin-top to padding-top.

Why isn't margins set relative to their parents? Is this the standard behavior of margin?

Cheng
  • 16,824
  • 23
  • 74
  • 104
  • http://stackoverflow.com/questions/5958699/difference-between-margin-and-padding – silviagreen Feb 27 '16 at 10:24
  • 1
    @silviagreen I did read some of the related answers on stackoverflow, but the emphasis that these answers give is `margin is the space outside the border` which is quite easy to understand. But what I don't get why margin is not apply in relation to its parent element in my example. Is this just how margin works? or did I do something wrong in my code? – Cheng Feb 27 '16 at 10:27

1 Answers1

1

Margins of block level elements fall outside the bounds of their container by default. To make sure they stay inside, you need to make the container a block formatting context root.

There are several ways to do this. One is to give the container a property of overflow:hidden

.container
  //existing code
  overflow: hidden

http://codepen.io/anon/pen/pyoeJO

It's a heady subject, and too complex to explain here, but if you're interested in the mechanics of why elements behave the way they do, I recommend learning about the visual formatting model and block formatting contexts in particular (for starters).

http://www.sitepoint.com/understanding-block-formatting-contexts-in-css/

https://www.w3.org/TR/CSS21/visuren.html#block-formatting

symlink
  • 11,984
  • 7
  • 29
  • 50
  • Thanks for the links. I really hope css can be more explicit about these little things which are not commonly mentioned in tutorials – Cheng Feb 27 '16 at 10:36
  • I agree. The upside is if you study the W3C 2.1 specs, you'll be way ahead of the curve. – symlink Feb 27 '16 at 10:41