learn2kode.in

CSS Margin

Margins are used to create space outside the border of an element. They help control layout, spacing, and alignment between elements on a webpage. Margins are completely transparent and do not have background color.

What is Margin?

Margin is the space outside an element’s border. It affects how far the element stays from surrounding elements.

Example

[ Margin ]
[ Border ]
[ Padding ]
[ Content ]

CSS Margin Properties

Margin Value Types

You can set margins using:

Example: Setting Individual Margins

.box {
  margin-top: 20px;
  margin-right: 10px;
  margin-bottom: 30px;
  margin-left: 5px;
}

Example: Shorthand Margin

.box {
  margin: 20px 10px 30px 5px; /* top right bottom left */
}

Other shorthand forms:

Centering with Margin Auto

.container {
  width: 300px;
  margin: 0 auto;
}

This centers the element horizontally.

HTML Table for CSS Margin Properties

Property Description
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 Shorthand for all margin properties