Utilizor
Contact Us

CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

Example 1: Margin - Individual Sides

CSS has properties for specifying the margin for each side of an element:

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left
This element has a margin of 50px on all sides.

Example 2: Margin - Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one single property.

margin: 25px 50px 75px 100px;
(top right bottom left)

Example 3: The auto Value

You can set the margin property to auto to horizontally center the element within its container.

The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

This div is centered.

Example 4: The inherit Value

This example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):

This paragraph has an inherited left margin (from the div element).

Example

div {
  margin: 25px 50px 75px 100px;
}

.center {
  margin: auto;
  width: 50%;
}