CSS: Padding and Margin

koralarts

Karl Castillo

Posted on April 19, 2020

CSS: Padding and Margin

There are plenty of ways you can provide spacing between your elements and content. Two of them are padding and margin.

Padding

Padding as mentioned before in the Box Model is the spacing between the actual content and the border.

There are different ways we could write the padding property values.

div {
  padding: 10px; /* All sides */
  padding: 10px 5%; /* Vertical Horizontal */
  padding: 10px 20px 30em; /* Top Horizontal Bottom */
  padding: 10px 20px 30rem 40px; /* Top Right Bottom Left */

  padding-left: 10px; /* Left */
  padding-right: 10px; /* Right */
  padding-top: 10px; /* Top */
  padding-bottom: 10px; /* Bottom */
}
Enter fullscreen mode Exit fullscreen mode

Padding also has special values that can be used.

  • %: percentage relative to the width of the container
  • initial: defaults to 0
  • inherit: padding value of the containing element
  • unset: removes the value

Gotcha

Not all display types treat padding the same.

Margin

Padding as mentioned before in the Box Model is the spacing between the element and another element.

There are different ways we could write the padding property values.

div {
  margin: 10px; /* All sides */
  margin: 10px 5%; /* Vertical Horizontal */
  margin: 10px 20px 30em; /* Top Horizontal Bottom */
  margin: 10px 20px 30rem 40px; /* Top Right Bottom Left */

  margin-left: 10px; /* Left */
  margin-right: 10px; /* Right */
  margin-top: 10px; /* Top */
  margin-bottom: 10px; /* Bottom */
}
Enter fullscreen mode Exit fullscreen mode

Inline

Similar to padding, margin doesn't behave as expected when the element is inline and its container is block. Inline elements don't show vertical margins even though its assigned.

Collapsing Margin

If elements aligned vertically have margins, the margin that value that will be used will be the bigger of the two instead of adding both values. This only works if you're

Gotcha!

Margins don't collapse if the containing block is display flex or grid because these two display types put its child elements in individual boxes.

💖 💪 🙅 🚩
koralarts
Karl Castillo

Posted on April 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related