CSS, margin vs. padding.

Sarah O’Brien
3 min readJan 19, 2018

--

When I was a newbie to CSS, I used to get margin and padding confused all the time. This is information I now take for granted because I know it and it’s like second nature, recently though I was working on a project with more junior developers and I noticed they were consistently using margin and padding incorrectly, I realised it might seem obvious to me but to those starting out with CSS it can be confusing. I hope to explain them both here and provide some clarity for any one who is confused, as I once was.

Margin:

Margin is a CSS property for defining space around an element, so outside the element. An example might be creating space between two divs. The example below shows two divs without any margin, so there is no space between them.

Example:

<div>
This div has no margin!
</div>
<div class=”space”>
This div has a margin!!
</div>
div {
border: 2px solid #000;
width: 100px;
background-color: #2471A3;
color: #fff;
font-family: Arial;
}
No margin or padding.

Now let’s add a margin.

We added a margin.
.space{
margin: 20px;
}

We can add a margin to all sides by setting the property and giving it one value like above, or we can specify exactly which sides and use multiple values, the properties are margin-top, margin-bottom, margin-right, margin-left, or for short we can give the margin property multiple values and it will apply it to each side. e.g. margin: 20px 10px 20px 10px; will apply a margin of 20px to the top, 10px to the right, 20px to the bottom and 10px to the left. It applies it in clockwise direction, TRBL, (top, right, bottom, left).

Padding

Padding is for creating space around an elements content, so inside the element. Looking at our simple example above there’s now space between our divs but the content inside still looks pretty squashed. We can fix this by adding some padding. We’ll modify our space class to add padding.

We added some padding.
.space{
margin: 20px;
padding: 20px;
}

Like margin, we can add padding to all sides by specifying one value, or specify multiple values, or use the explicit property for each side.

To summarise margin is outside the element and padding is inside the element. I hope this makes things a bit clearer. Happy Coding :)

--

--

Sarah O’Brien

Front end developer. JavaScript is my jam. I'm one of those weirdos who actually likes CSS. Coding related posts. Follow my journey on instagram @sarah.codes