How to set the CSS margin properties in one declaration?

The margin property defines the space around an HTML element. It is possible to use negative values to overlap content. It specifies a shorthand property for setting the margin properties in one declaration.

Syntax

margin: value;
margin: top right bottom left;
margin: top horizontal bottom;
margin: vertical horizontal;

Margin Value Patterns

The margin property accepts 1 to 4 values with different behaviors:

Values Result Example
1 value All sides same margin: 20px
2 values vertical | horizontal margin: 10px 5px
3 values top | horizontal | bottom margin: 15px 4% -10px
4 values top | right | bottom | left margin: 10px 5px 15px 20px

Example

You can try to run the following code to set margins:

<html>
  <head>
  </head>
  <body>
    <p style="margin: 20px; border:2px solid yellow;">
      All four margins will be 20px
    </p>
    <p style="margin: 15px 4% -10px; border:2px solid red;">
      Top margin will be 15px, left and right margin will be 4% of the total width of the document, bottom margin will be -10px
    </p>
    <p style="margin: 10px 5px 15px 20px; border:2px solid blue;">
      Top: 10px, Right: 5px, Bottom: 15px, Left: 20px
    </p>
  </body>
</html>

Using Negative Margins

Negative margins can overlap elements or pull content closer:

<html>
  <head>
  </head>
  <body>
    <div style="background: lightblue; padding: 10px; margin: 20px;">
      First div with normal margin
    </div>
    <div style="background: lightcoral; padding: 10px; margin: -10px 20px 20px;">
      Second div with negative top margin (overlaps above)
    </div>
  </body>
</html>

Key Points

  • Values can be in pixels (px), percentages (%), or other CSS units
  • Percentage values are relative to the parent element's width
  • Negative margins pull elements closer or create overlaps
  • The shorthand follows clockwise order: top, right, bottom, left

Conclusion

The CSS margin shorthand property provides an efficient way to set spacing around elements. Use 1-4 values to control all sides at once, with negative values creating overlapping effects when needed.

Updated on: 2026-03-15T23:18:59+05:30

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements