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

HTML How to Make a Website Styling Web Pages and Navigation Build Navigation with Unordered Lists

Ryan Maneo
Ryan Maneo
4,342 Points

Difference between margin and padding?

I'm a bit confused on this... what's the difference? They all seem to provide a buffer area between elements... could someone please define each and explain the purpose of each one?

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Padding is the space that's inside the element between the element and the border. Padding goes around all four sides of the content and you can target and change the padding for each side with CSS. Margin is the space between the border and next element.

[source]

first you have the element in the center. the padding is outside that. the border is outside that. the margin is outside that. Padding will make the space around the element larger. Margin will push the element with it's padding away from other elements.

<style>
#p1 {
  padding: 30px;
  background: orange;
  margin: 30px;
}
#p2  {
  padding: 5px;
  background: green;
  margin: 0px;
}
#p3  {
  padding: 5px;
  background: black;
  color: white;
  margin: 0px;
}

</style>
<p id="p1">hi</p>
<p id="p2">hi</p>
<p id="p3">hi</p>

If you copy and paste this into your editor and then view it in a browser you will see:

  • the orange around the first hi is the padding.
  • you will also notice that it pushes the other elements away.
  • this is the margin
  • notice the 2nd and third p
  • they are nestled right next to each other
  • they have 0 margin
  • also notice they have green and black backgrounds
  • this is the padding.

I just noticed Chris gave a very concise answer. Still, you can play with the code I put there to get a feel for margin and padding