views:

1123

answers:

6

When writing CSS, is there a particular rule or guideline that should be used in deciding when to use margin and when to use padding?

+7  A: 

Here's a great article that was posted on Smashing Magazine recently which gives the best description I've seen (includes nice pictures):

http://www.smashingmagazine.com/2009/10/05/mastering-css-coding-getting-started/#CSS-Basics1

idea
Direct link to padding vs margin section: http://www.smashingmagazine.com/2009/10/05/mastering-css-coding-getting-started/#CSS-Basics1
donut
Good one, cheers ;)
idea
+22  A: 

Margin is on the outside of block elements while padding is on the inside.

use margin to separate the block from things outside it, padding to move the contents away from the edges of the block.

John Boker
+2  A: 

You might find this useful :)

Remember that when you use padding, padding adds to the containers width/height.

twodayslate
Good tip about padding adding to containers size.
TandemAdam
A: 

One thing to note is when auto collapsing margins annoy you (and you are not using background colours on your elements), something it's just easier to use padding.

alex
+1  A: 

the thing about margins is that you don't need to worry about the element's width. like when you give something {padding: 10px;} you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.

so i generally start of by using paddings to get everything 'packed' and then use margins for minor tweaks.

another thing to be aware of paddings are more consistent on different browsers and IE doesn't treat negative margins very well.

pixeltocode
+2  A: 

Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html>


<style>
    .outer {
        padding:10px;
        background:red;
    }

    .inner {
        margin:10px;
        padding:10px;
        background:blue;
        border:solid white 1px;
    };

</style>

<script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;

<body>

    <div class="outer">
        <div class="inner" style="position:relative; height:0px; width:0px">

        </div>
    </div>

    <script type="text/javascript">

        $(".outer").click(function(e) { alert("outer"); e.stopPropagation(); });
        $(".inner").click(function(e) { alert("inner"); e.stopPropagation(); });

    </script>

</body>
</html>
Frank Schwieterman