Cascading Style Sheet (CSS)

CSS Margins

The margin is the blank space around an element provided to position the element comfortably. The additional space added, does not have any background color, it is completely transparent.

You can set a margin around an element by using the margin property.

Syntax:

margin: value in px, em or % | inherit

Where margin value is either a length, percentage value, auto, or inherit from the parent element.

Here is a video to explain all about margin property.

Live Example →


Video Transcript:

If two values are provided in the margin property, the first will set the top and bottom margins and the second value applies to the right and left margins. Similarly, if three values are provided to the margin shorthand, the first applies to the top margin, second to the right and left margins, while the third value applies to the bottom margin. Notice how the unspecified margin is inferred from the value defined for its opposite side. If you wish to set the values for all four sides, you can set them in this order: top, right, bottom, left.

This is illustrated in the following example:

margin: 25px 50px 75px 100px;

  • margin from the top will be 25px
  • margin from the right will be 50px
  • margin from the bottom will be 75px
  • margin from the left will be 100px

margin: 25px 50px 75px;

  • margin from the top will be 25px
  • margin from the right and left will be 50px
  • margin from the bottom will be 75px

margin: 25px 50px;

  • top and bottom margins: 25px
  • right and left margins: 50px

margin: 50px;

  • margin on all the sides will be 50px

Elements may have default margins on them and these values may vary. If you want to reset all margins to zero and then add your own margins, you can use a wildcard rule like *{ margin: 0; } to clear all margins. Also note than margin values can be negative.

This is compatible with CSS1, CSS2 and CSS3 along with following Web Browsers,

  • IE 6+
  • Firefox 1+
  • Opera 3.5+
  • Safari 1+
  • Chrome 1+

So, that's all about margins. This was pretty easy, right? Let’s move ahead to positioning elements.