Home
 › Learn
 › CSS

CSS Margins

CSS: Learn about css margins

Updated At: November 2024
CSS Margins

The CSS margin properties are effectively employed to create additional spacing around elements, extending beyond any explicitly defined boundaries.

CSS Margin properties

An HTML element has four sides, so we have four margin properties for each side.

  • margin-top
  • margin-bottom
  • margin-left
  • margin-right

⁠⁠

Playground Example: To make things simpler, you can click the button below to open the playground, which comes with pre-filled HTML and CSS.

In the editor, you will see HTML, CSS, and JS input on the left/top, and the output on the right/bottom.

⁠⁠

⁠⁠Below is the syntax for adding margins:

Selector {
  margin-top: value;
  margin-bottom: value;
  margin-left: value;
  margin-right: value;
}⁠
  • The selector can be any one or more of those discussed previously in CSS Selectors.
  • " margin-*" is the property key
  • "value" can be in pixels, percentage, auto or inherit.

⁠⁠

Example:

/* margin-top */
.marginTop {
  margin-top: 10px;
}

Try changing the value in the playground and observe the margin change.

It is not required to add all four margin properties; we can add them based on what is required.

⁠⁠

CSS Margin Shorthand

The shorthand property is used to specify all margin properties in a single declaration.

⁠⁠⁠Below is the syntax for adding margin shorthand:

Selector {
  margin: margin-top margin-right margin-bottom margin-left 
}⁠

  • The selector can be any one or more of those discussed previously in CSS Selectors.

  • "margin" is the property key

  • "value" can be a mix of all possible values. Keep in mind that the order of values matter.

Example:

/* margin-shorthand */
.shortHandStyle {
  margin: 10px 20px 10px 20px;
}

Note: Shorthands are very common in CSS, and we will encounter them more often as we move forward.

CSS Margin Shorthand - Variations

The margin shorthand property can have different variations.

Here are the various syntax variations for margin shorthand.

When left and right margins are equal

/* When left and right are equal */⁠
Selector {
  margin: margin-top margin-right margin-bottom
}⁠


⁠Example:

/* margin-shorthand Three Value */
.shortHandThreeValue {
  margin: 10px 20px 10px;
}

When left and right margins are equal and top and bottom are equal

/* When left = right and top = bottom */⁠
Selector {
  margin: margin-top margin-right
}⁠

⁠Example:

/* margin-shorthand Two Value */
.shortHandTwoValue {
  margin: 10px 20px;
}

When all margins are equal

/* When left = right = top = bottom */⁠
Selector {
  margin: margin-top
}⁠

⁠Example:

/* margin-shorthand Single Value */
.shortHandSingleValue {
  margin: 10px;
}

Want to practice more? Click here for more hands-on exercise.

⁠⁠References:

JavaScript

    React

      NextJS

        HTML

          CSS

            Sign up for our newsletter.

            Copyright © theHardCoder 2023 - 2025