CSS Margin

Subject: css

CSS Margin

CSS Margin is used to create space outside the border of an HTML element. It helps control the distance between elements and is essential for proper page layout and spacing.

Margins are transparent and do not have background color or borders. You can set margins for each side of an element—top, right, bottom, and left—either individually or using shorthand.


CSS Margin Properties

  • margin-top: Sets the top margin.
  • margin-right: Sets the right margin.
  • margin-bottom: Sets the bottom margin.
  • margin-left: Sets the left margin.
  • margin: A shorthand to set all four margins in one line.

Example: Margin Usage in CSS


Margin Shorthand Syntax

You can use the margin shorthand in several ways:


Using auto for Centering

Margins can also take the value auto, especially useful for horizontally centering block-level elements:

This centers the element horizontally within its container.


Key Takeaways

  • Margins create space outside an element’s border.
  • You can define margins for each side individually or all at once using the margin shorthand.
  • Use auto to center block elements horizontally inside a container.
  • Margins collapse vertically — adjacent vertical margins may merge (called margin collapsing).
  • Margins are always transparent and do not affect the background or border styles.