CSS Margins

DevwaresDevwares
2 min read

CSS Margins

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

Contrast Bootstrap UI Kit

Margin - Individual Sides

CSS allows you to set margins for individual sides of an element:

div {  margin-top: 50px;  margin-right: 30px;  margin-bottom: 50px;  margin-left: 80px;}

In this example, the top margin is 50px, the right margin is 30px, the bottom margin is 50px, and the left margin is 80px.

Shorthand Property: Margin

The margin property is a shorthand property for margin-top, margin-right, margin-bottom, and margin-left.

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

In this example, the top margin is 25px, the right margin is 50px, the bottom margin is 75px, and the left margin is 100px.

You can also provide less than four values:

  • If you provide one value, it applies to all sides. For example, margin: 25px;.

  • If you provide two values, the first value applies to the top and bottom margins, and the second value applies to the right and left margins. For example, margin: 25px 50px;.

  • If you provide three values, the first value applies to the top margin, the second value applies to the right and left margins, and the third value applies to the bottom margin. For example, margin: 25px 50px 75px;.

Auto Value

When the margin property has an auto value, the browser automatically adjusts the margins to center the element within its container.

div {  width: 300px;  margin: auto;}

In this example, the div element is centered within its container.

Negative Values

You can also set the margin property to a negative value.

div {  margin: -25px;}

In this example, the div element will overlap the elements before and after it by 25px.

0
Subscribe to my newsletter

Read articles from Devwares directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Devwares
Devwares