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 How to Make a Website Styling Web Pages and Navigation Polish the Navigation and Footer

Ashford Morgan
Ashford Morgan
1,973 Points

When should I use margin and padding with what measurement?

Having trouble determining when to use margin or padding from the videos. Also I'm confused about when to use percentages or pixels for these properties.

1 Answer

Margin is the space you want to have outside a given element. Padding is the space you want to have within a given element.

For example, if you have a box that is 200 by 200 pixels. If you give it a margin of 15 pixels, the box will push everything by 15px out of the way. So if you had 1 of these boxes and below it a picture; the picture would not "touch" the box, but instead leave a breathing-space of 15px.

Padding has to do with the content of the box. If you have text inside the box, and give the box a 3px padding the text will leave a breathing-space of 3px from the edge of the box's edges.

Here is a code example: http://codepen.io/anon/pen/kyJnA change the margin from 0 to, say, 10px and you will see that they'll get some spacing. Try the same on padding.

Percentages should be used when you want to give an element a compared-size to its' parent element. For example, if you have a box and you want a picture inside it to take up half its' width - you'd set a width of 50% on the image. The image will then take half the width of the box - even if the box changes size. Fixed pixel sizes should only be used when you want to give an element a non-dynamic size that doesn't ever change dimensions.

Here is a code example of percentages and fixed pixel sizes: http://codepen.io/anon/pen/gmJhp

The grey box has a width of 50% - which means it will take up 50% of the screens' width. If you resize the window - so will the box so it's always half the width of the window. The car has a width of 25% - which means it will always be 25% of the width of its' parent-element - in this case the grey box. So the car will be 25% the width of the grey box. The green box has a fixed width however of 100px - this won't change ever, regardless of the width of the window and parent-elements.

Try opening the above link in windowed-mode and resize the width of the window to see how things change.

Hope this helps :) Good luck!

Ashford Morgan
Ashford Morgan
1,973 Points

Thank you, that was really helpful!!!