What's the Shorthand for the CSS margin Property?

CSS margin property can be written in shorthand form in the following ways:

  1. As a Single Value;
  2. As Two Values;
  3. As Three Values;
  4. As Four Values.

CSS margin Shorthand With One Value

When only one value is specified for margin, it applies the value to all four sides:

margin: 10px; /* margin-top: 10px; margin-right: 10px; margin-bottom: 10px; margin-left: 10px; */

CSS margin Shorthand With Two Values

When two values are specified for margin:

  1. First value applies to the top and bottom margin;
  2. Second value applies to the left and right margin.

For example:

margin:
    10px /* margin-top: 10px; margin-bottom: 10px; */
    20px /* margin-right: 20px; margin-left: 20px; */
;

CSS margin Shorthand With Three Values

When three values are specified for margin:

  1. First value applies to the top margin;
  2. Second value applies to the left and right margin;
  3. Third value applies to the bottom margin.

For example:

margin:
    10px /* margin-top: 10px; */
    20px /* margin-right: 20px; margin-left: 20px; */
    30px /* margin-bottom: 30px; */
;

CSS margin Shorthand With Four Values

When four values are specified for margin:

  1. First value applies to the top margin;
  2. Second value applies to the right margin;
  3. Third value applies to the bottom margin;
  4. Fourth value applies to the left margin.

For example:

margin:
    10px /* margin-top: 10px; */
    20px /* margin-right: 20px; */
    30px /* margin-bottom: 30px; */
    40px /* margin-left: 40px; */
;

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.