Douiri

Visualizing CSS Margin and Padding For beginners

written by idriss douiri profile picture Idriss Douiri

updated on

3 min read

css margin and padding article poster

The Box Model

To fully understand the role of padding and margin in CSS we need to know what is the box model. In CSS every HTML element is treated as a box consisting of multiple layers: the content box, padding box, border box, and margin box. The padding box is between the content box and the border box, while the margin box is outside the border box.

css box model break down

Margin VS Padding

The margin is the outer space surrounding an element, while the padding is the inner space of an element.

Move the sliders to see how each property affects the box:

Content 🙂
Another Content
margin

The margin and padding properties are shorthand properties that control all four sides of the box in one line. Thus, padding: 5px; is equivalent to padding: 5px 5px 5px 5px; where each value represents a side of the box in clockwise order, starting from the top and moving to the right, bottom, and left.

css margin and padding value order

So writing margin: 5px 10px 0 10px; is translated to:

 margin-top: 5px;
 margin-right: 10px;
 margin-bottom: 0;
 margin-left: 10px;

Alternatively, you can specify one, two, or three values instead of four, which works as follows:

  • one value for: all sides equally
  • two values for: top-bottom right-left
  • three values for: top right-left bottom

Example:

CSS Shorthand VS Longhand

In CSS when working with properties that have more than one version you need to be aware of this conflict. Imagine you want to push an element from the top by 1rem and place it in the center using margin: auto, what would you do?

Here is one way you could think of it:

.box {
	margin-top: 1rem;
	margin: auto;
}

This might look fine, but it won’t output the expected result as the shorthand will override the longhand property because the last wins. but if we reverse the two lines then it will work and the longhand will override as it is the last property

.box {
	margin: auto;
	margin-top: 1rem;
}

The power of margin: auto

Unlike the padding, the margin accepts the auto keyword, which only works in the inline direction (left to right) and allows the browser to automatically calculate and use the remaining space as a margin, pushing the box left, right, or even to the center.

Try setting both left and right and see the how they will affect the box:

margin-left: auto; /* margin-right: auto; */

Margin or Padding: When to Use Each

If you can’t differentiate between the margin and the padding yet, the easiest thing to do is to experiment. use one, and if it doesn’t work as expected, then use the other. By repeating this simple trick each time you get confused, you will eventually use the right property at the right time.