DEV Community

loading...
Cover image for Margin vs Padding in CSS Explained

Margin vs Padding in CSS Explained

arbaoui_mehdi profile image Arbaoui Mehdi πŸ‡²πŸ‡¦ ・2 min read

Introduction

Differentiating between margin and padding css properties can sometimes be confusing, the short description of these two properties is that padding can be considered as an internal element which helps to create space around the element (outside the border), in the opposite margin is used to control the space outside the container (inside the border).

This an example of what’s already said:

Alt Text

The image present the box model, this box is geometrically defined by the following properties: width, height, border, padding and margin.

Margin

We can denote the length of the margin property by using px pixel, em or %, choosing one of these unit depends on how you’re managing the size and the positioning of your elements.

To set the size of the margin area we have the choice to use the suffixes -top (top), -right (right), -bottom (bottom) and -left (left) to define all four sides of an element.

Alt Text

.element {
  margin-top: 10px;
  margin-right: 5px;
  margin-bottom: 0;
  margin-left: 15px;
}

We have also the choice to set all of the values respectively (top, right, bottom and left) in one line:

Alt Text

If the top and bottom and right, left has the same values we'll have this presentation:

Alt Text

Padding

padding share the same principal of the margin property except that it creates space around the element inside the border, instead of outside the element.

Alt Text

And this is an example that defines the sizes of the padding area on all four sides in one line, then using the direction suffix.

/* One Line Presentation */
.element {
  padding: 15px 20px 13px 8px;
}

/* Direction Suffix */
.element {
  padding-top: 15px;
  padding-right: 20px;
  padding-bottom: 13px;
  padding-left: 8px;
}

Discussion (2)

pic
Editor guide
Collapse
traumastronaut profile image
thimo

Great explanation!

As a shorthand notation you can also have 3 values whereas the the order is TOP, (LEFT & RIGHT), BOTTOM :)

Collapse
arbaoui_mehdi profile image
Arbaoui Mehdi πŸ‡²πŸ‡¦ Author

Yeah, thank your for that, I'll update the article and add this part.