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

why use margin-top instead of padding-top? is there a difference?

can i know why this code example from css class uses margin-top to create the spacing instead of padding-top? css https://imgur.com/5ne5XWQ

3 Answers

Hey there TzeYang,

Just to further add on this, there is a huge difference between Margin and padding. This article on W3schools shows a picture of the Box model. Using this as a reference, remember the following:

Lets say you have a DIV with the class "box" and in your CSS you give it the following properties:

.box {
  border: solid 2px red;
}

This box is going to have a solid 2px red border around it and we'll use this border as a reference point. Now, lets say you add a margin: 5px; to this rule. This Box you have will now have 5px of margin on the OUTSIDE of the border pushing it away from other content. If you were to add a padding: 5px to the rule instead, you would see the space between the content and its border increase by 5px.

In short, Padding increases /decreases the distance between the box's content and the border, and the Margin increases /decreases the space between the border, and other objects.

I hope this helps, don't forget to select a best answer to mark this question as resolved!

Cheers and Happy Coding! :beers:

-Jon

Hi TzeYang,

Let's say we have a div with a background-color of blue in the middle of a layout. Using margin-top pushes your entire div away from the div above. If you're using padding-top instead, while it might look like if the content inside of the div moves away from the top, the background-color area on the top of the div will grow if you add padding-top. So using padding won't move your div away from other elements, margin will do this.

I hope that helps

Jonas

Thanks for your help!