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.

Example
Try this code

Individual Margins

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

Example
Try this code

Shorthand Margin Property

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

Example
Try this code
/* top right & left bottom  */     
div {
  margin: 10px 20px 15px;
}
/* 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.

Example
Try this code

Negative Margin

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

Example
Try this code

Best Practices for Margins

Common Mistakes with Margins

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