2455

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?

TylerH
  • 19,065
  • 49
  • 65
  • 86
Alex Angas
  • 56,458
  • 39
  • 130
  • 203

16 Answers16

1678

TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.

To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't.

Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element and is always preserved.

So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.

Thus the content of the two elements will end up being 2em apart.

Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.

So in this example, you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.

This can be really useful when you know that you want to say 1em of spacing around an element, regardless of what element it is next to.

The other two big differences are that padding is included in the click region and background color/image, but not the margin.

div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }
div.padding > div { padding-top: 20px; }
div.margin > div { margin-top: 20px; }
<h3>Default</h3>
<div class="box">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>

<h3>padding-top: 20px</h3>
<div class="box padding">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>

<h3>margin-top: 20px; </h3>
<div class="box margin">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>
Black
  • 12,789
  • 26
  • 116
  • 196
pavon
  • 16,449
  • 1
  • 20
  • 23
  • 55
    +1 When styling typography and abritary sequences of paragraphs, headings and lists it's _almost always_ better to space the elements with margins because of the adjacent margin collapsing behaviour. – Pete B Nov 08 '13 at 11:01
  • 21
    Why is it that vertical margins collapse while horizontal ones don't? That could confuse a lot of people – Marcos Pereira Dec 17 '14 at 21:58
  • 19
    The vertical margins only collapse for block elements. For inline block elements the margins are added both vertically and horizontally. So I am not sure that it is an issue that horizontal margins don't collapse on block elements since they fill their container anyways. – Mike Feb 16 '15 at 22:19
  • 6
    "Why is it that vertical margins collapse while horizontal ones don't?" there is no mechanism for having block elements side by side to each other without using floats - whose margins never collapse anyway (even vertical) or absolute positioning, where there's obviously no collapsing, or inline-block, which uses a different model where it's considered inline and content (spaces, text) is significant, or other things like tables, flexbox, columns where the gap between columns has special behaviour. So in short there is no place that horizontal margin collapsing *could* be used even if possible – thomasrutter Apr 13 '15 at 01:48
  • 7
    Also you should take note that padding is included in total width/height the element, when used with `box-sizing: border-box;` so if you have `width: 100px; padding-left: 20px;` the total width will still be 100px but the area for content is reduce by 20px, unlike `box-sizing: content-box;` where padding is separate in calculating content width which makes your total width 120px in content-box; – Jomar Sevillejo Nov 09 '15 at 06:19
1531

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

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

enter image description here

davidcondrey
  • 29,530
  • 14
  • 105
  • 129
John Boker
  • 78,333
  • 17
  • 93
  • 129
605

The best I've seen explaining this with examples, diagrams, and even a 'try it yourself' view is here.

The diagram below I think gives an instant visual understanding of the difference.

enter image description here

One thing to keep in mind is standards compliant browsers (IE quirks is an exception) render only the content portion to the given width, so keep track of this in layout calculations. Also note that border box is seeing somewhat of a comeback with Bootstrap 3 supporting it.

Community
  • 1
  • 1
Scott
  • 16,077
  • 13
  • 69
  • 118
  • 4
    http://www.w3.org/TR/CSS2/box.html#box-dimensions and the picture from w3 http://www.w3.org/TR/CSS2/images/boxdim.png – JP Hellemons Oct 10 '12 at 14:05
112

There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.

Imagine block elements as picture frames hanging on a wall:

  • The photo is the content.
  • The matting is the padding.
  • The frame moulding is the border.
  • The wall is the viewport.
  • The space between two frames is the margin.

With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.


1 You can alter this behavior with the box-sizing attribute.

stvnrynlds
  • 1,819
  • 1
  • 10
  • 19
  • Actually I don't agree on `box-sizing: border-box` making "the space for the content smaller". Here is a fiddle with 2 boxes where, if I kept padding the same and added "Active", then "Deactivate" on hover, it did not matter if I used `box-sizing`. It would still expand the box. I had to max out the padding to the longest the box would expand to, then use trial and error to come up with a matching combination for the other words going into the box that would keep it the same width for each word: http://jsfiddle.net/navyjax2/ngzqqjah/ – vapcguy Mar 03 '15 at 03:19
  • 3
    Hey vapcguy, thanks for your input. My statement is generally true, when width or height is declared for an element, while an element with undeclared dimensions is not really affected by `border-box` (see: http://jsfiddle.net/8yravLmL/1/). I'll make my answer more nuanced to avoid confusion. – stvnrynlds May 13 '15 at 17:17
88

MARGIN vs PADDING :

  1. Margin is used in an element to create distance between that element and other elements of page. Where padding is used to create distance between content and border of an element.

  2. Margin is not part of an element where padding is part of element.

Please refer below image extracted from Margin Vs Padding - CSS Properties

Margin vs Padding

wpercy
  • 8,491
  • 4
  • 29
  • 39
Touhid Rahman
  • 2,279
  • 19
  • 22
  • Referencing the border, rather than the rather vague 'Margin is on the outside of block elements while padding is on the inside.' outside/inside of what? And outside/inside suggests a static position, not that it affects the size of the containing element. This answer clarified it for me. – nicodemus13 May 14 '14 at 21:09
53

From https://www.w3schools.com/css/css_boxmodel.asp

Explanation of the different parts:

  • Content - The content of the box, where text and images appear

  • Padding - Clears an area around the content. The padding is transparent

  • Border - A border that goes around the padding and content

  • Margin - Clears an area outside the border. The margin is transparent

Illustration of CSS box model

Live example (play around by changing the values): https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel

Pang
  • 8,605
  • 144
  • 77
  • 113
Pulkit Anchalia
  • 706
  • 6
  • 8
36

It's good to know the differences between margin and padding. Here are some differences:

  • Margin is outer space of an element, while padding is inner space of an element.

  • Margin is the space outside the border of an element, while padding is the space inside the border of it.

  • Margin accepts the value of auto: margin: auto, but you can't set padding to auto.

  • Margin can be set to any number, but padding must be non-negative.

  • When you style an element, padding will also be affected (e.g. background color), but not margin.

MAChitgarha
  • 2,189
  • 2
  • 19
  • 30
33

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.

$(".outer").click(function(e) {
  console.log("outer");
  e.stopPropagation();
});

$(".inner").click(function(e) {
  console.log("inner");
  e.stopPropagation();
});
.outer {
  padding: 10px;
  background: red;
}

.inner {
  margin: 10px;
  padding: 10px;
  background: blue;
  border: solid white 1px;
}
<script src="http://code.jquery.com/jquery-latest.js"></script>

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

  </div>
</div>
Paul Roub
  • 35,100
  • 27
  • 72
  • 83
Frank Schwieterman
  • 23,338
  • 15
  • 87
  • 123
32

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 off by using paddings to get everything 'packed' and then use margins for minor tweaks.

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

Serp C
  • 766
  • 1
  • 7
  • 23
pixeltocode
  • 5,196
  • 11
  • 49
  • 69
30

The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.

enter image description here

it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.

note that some times you have to use margin.

Mohammad Golahi
  • 349
  • 3
  • 8
  • 1
    "note that some times you have to use margin" Thats the question. When are these times? – Black Aug 19 '20 at 07:58
18

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
  • 438,662
  • 188
  • 837
  • 957
15

Advanced Margin versus Padding Explained

It is inappropriate to use padding to space content in an element; you must utilize margin on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to using margin which works perfectly in Internet Explorer 4.

There are two exceptions when using padding is appropriate to use:

  1. It is applied to an inline element which can not contain any child elements such as an input element.

  2. You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.

When you have a 100% width element with padding: 50px; you effectively get width: calc(100% + 100px);. Since margin is not added to the width it will not cause unexpected layout problems when you use margin on child elements instead of padding directly on the element.

So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.

John
  • 10,154
  • 9
  • 79
  • 143
14

First let's look at what are the differences and what each responsibility is:

1) Margin

The CSS margin properties are used to generate space around elements.
The margin properties set the size of the white space outside the border. With CSS, you have full control over the margins.
There are CSS properties for setting the margin for each side of an element (top, right, bottom, and left).


2) Padding

The CSS padding properties are used to generate space around content.
The padding clears an area around the content (inside the border) of an element.
With CSS, you have full control over the padding. There are CSS properties for setting the padding for each side of an element (top, right, bottom, and left).

So simply Margins are space around elements, while Padding are space around content which are part of the element.

Margin and Padding

This image from codemancers shows how margin and borders get togther and how border box and content-box make it different.

Also they define each section as below:

  • Content - this defines the content area of the box where the actual content like text, images or maybe other elements reside.
  • Padding - this clears the main content from its containing box.
  • Border - this surrounds both content and padding.
  • Margin - this area defines a transparent space that separates it from other elements.
Community
  • 1
  • 1
Alireza
  • 83,698
  • 19
  • 241
  • 152
  • This answer appears to have copied and pasted from somewhere else. Included link from "codemancers" has nothing to do with answer. – Alex Angas Jun 02 '17 at 06:09
  • 2
    Alex, the pic and part of from the answer which highlighted are from codemancers, please make sure about the things before you leave a comment and vote – Alireza Jun 02 '17 at 06:22
8

I always use this principle:

box model image

This is the box model from the inspect element feature in Firefox. It works like an onion:

  • Your content is in the middle.
  • Padding is space between your content and edge of the tag it is inside.
  • The border and its specifications
  • The margin is the space around the tag.

So bigger margins will make more space around the box that contains your content.

Larger padding will increase the space between your content and the box of which it is inside.

Neither of them will increase or decrease the size of the box if it is set to a specific value.

TylerH
  • 19,065
  • 49
  • 65
  • 86
Bjamse
  • 154
  • 6
  • 14
6

Margin

Margin is usually used to create a space between the element itself and its surround.

for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.

Padding

I usually use when I've an element inside a border, <div> or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.

So briefly, it's situational; it depends on what you are trying to do.

TylerH
  • 19,065
  • 49
  • 65
  • 86
Mostafa Osama
  • 168
  • 2
  • 12
-1

Margin is outside the box and padding is inside the box

saurabhgoyal795
  • 1,043
  • 10
  • 11