Many intermediate and begginer CSS designers get confused when it comes to padding and margin values. What’s the difference? They both just shift stuff, so why the different names? Don’t they do the same thing?
Although the behavior of margin- and padding- is very similary, there is one important difference: margin- is on the outside of the element, and padding- is on the inside. What this means is, one will apply the whitespace shift “after” the element begins (padding), and the other will apply the whitespace “before” the element begins (margin). Many times there is no visible difference, but sometimes there is – a big one.
- Colored backgrounds. Imagine a div tag with a colored background. If you apply “padding-top: 10px” you’re going to lower the text by 10px – but this “lowering” is going to take place inside the colored div, which will start in the same place as it always did. In the end, your colored section will be 10px larger. If you had used the “margin-top” property instead, you would have lowered the entire div, and the text along with it. Your colored section would not change in size.
- Negative values. You can use “margin-left: -10px” and end up moving an element 10px over to the right – actually making it float on top (or under) the neighboring element, because you’re changing where the element begins (-10 from the left). But you can’t use negative values with “padding-” because then you’d be telling it something like “start the contents -10px before the container for this text even begins;” which obviously isn’t possible. You can drag the entire element over to the right (margins), but you can’t place the number 2 before the number 1 (padding), that’s just illogical!
That’s all you need to know about padding and margins, but it’s useful to remember one more thing: when “zeroing out” a element (to get rid of all default margins), be sure to set both the padding and margin to 0. Depending on which browser interprets your page, it may place the default spacing as either a margin or a padding, and you have to be sure you get them both.
thanks for imformation