Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Can the box inside "reach out" of the outer box?

I put my facebook logo inside "footer", found it was too close to the top of the footer, so I add something like .logo{ margin-top: 20em}(not this big number though, just want you to see the effect), and it moved the whole footer away! If I replace "margin" with "padding", it worked nicely.

In short: Say box B is inside box A, and box C is outside and on the top of Box A, when I change the margin of B, why does it affect the margin between A and C? Isn't it supposed to be an "internal affair" between A and B?

This is my fiddle link: http://jsfiddle.net/pgH2b/8/

2 Answers

Hi Yaxin,

It's not so much that it's "reaching out" but the 2 margins are combining into a single margin. When 2 margins are touching like that with nothing to separate them then they will combine. The margins collapse into each other.

It's the same thing when you have a series of paragraphs on your page. Say each one has both a 20px top and bottom margin. You don't get 40px of space between paragraphs. The bottom margin from one combines with the top margin from the next one and forms a single 20px margin.

To prevent this there needs to be some content, padding, or border between the margins to prevent them from touching each other.

If your footer for example had a 1px top border then that would be enough to separate the footer margin from the margin you put on .logo and then it would work the way you were hoping.

The micro clearfix hack is another way you can prevent this from happening: http://nicolasgallagher.com/micro-clearfix-hack/

See note #2 in the css comments as well as the explanation afterwards. If you were to apply this clearfix class to your footer then that would also prevent the margins from collapsing.

Here's a stackoverflow link about this subject with some links to the relevant parts of the w3c specification: http://stackoverflow.com/questions/2176520/why-would-margin-not-be-contained-by-parent-element

Pete England
Pete England
10,801 Points

Why not just add padding to the inside of the footer container? That way you aren't setting margins per image and its going to apply nicely to everything within the footer! You might also want to look into the box-sizing method or some of the intro to css courses

I know padding works.... Just wonder why margin doesn't....