CSS Margins

CSS margins are used to create space around HTML elements, outside of their borders. They allow you to control spacing between elements, improving layout and readability.

Margin Property

The margin property sets the space outside an element. It can take values in pixels, percentages, em units, or auto.

div {
  margin: 20px;
}

Individual Margins

You can set margins for each side of an element individually using: margin-top, margin-right, margin-bottom, and margin-left.

div {
  margin-top: 10px;
  margin-right: 15px;
  margin-bottom: 10px;
  margin-left: 15px;
}

Shorthand Margin Property

You can use the shorthand margin property to set all four sides in one line:

/* top right bottom left */
div {
  margin: 10px 15px 20px 25px;
}

/* top & bottom, left & right */
div {
  margin: 10px 20px;
}

/* all sides same */
div {
  margin: 15px;
}

Auto Margin

Setting margin: auto; can be used to center block-level elements horizontally.

div.centered {
  width: 50%;
  margin: 0 auto;
}

Negative Margin

Margins can also be negative, allowing elements to overlap or move closer than normal spacing.

div {
  margin-top: -10px;
}

Best Practices for Margins

Common Mistakes with Margins

Tip: Combine margin with padding to create balanced spacing for elements.