Cheng
Cheng

Reputation: 17904

CSS margin not set relative to its parent

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?

Upvotes: 1

Views: 512

Answers (1)

symlink
symlink

Reputation: 12209

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

Upvotes: 1

Related Questions