Margin - The margin in CSS

The margin feature in CSS is used to create spaces around the element, outside the borders. These properties will set the edge of each element (top, bottom, left, right).

The margin feature in CSS is used to create spaces around the element, outside the borders. These properties will set the edge of each element (top, bottom, left, right).

The edges of the margin in CSS

CSS has properties defining margins for each edge in an element:

  1. margin-top
  2. margin-right
  3. margin-bottom
  4. margin-left

All margin properties can have the following values:

  1. auto - browser calculates the margin
  2. length - determines the margin according to px, pt, cm .
  3. % - determines the margin in% of the width of the element
  4. inherit - determine the margin inherited from the parent element

Negative values ​​can be used. The following example creates different margins for the 4 sides of the element

:

 p { 
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}

Shortened feature of margin in CSS

To shorten the code, it is possible to include all properties in a single margin property, with its own properties:

  1. margin-top
  2. margin-right
  3. margin-bottom
  4. margin-left

If margin has 4 values

 margin: 25px 50px 75px 100px; 
  1. 25px upper margin
  2. right margin 50px
  3. margin below 75px
  4. left margin 100px
 p { 
margin: 25px 50px 75px 100px;
}

If the margin feature has 3 values

 margin: 25px 50px 75px; 
  1. 25px upper margin
  2. left and right margins 50px
  3. margin below 75px
 p { 
margin: 25px 50px 75px;
}

If margin has 2 values

 margin: 25px 50px; 
  1. upper margin and below 25px
  2. left and right margins 50px
 p { 
margin: 25px 50px;
}

If the margin property has 1 value

 margin: 25px; 
  1. All margins are 25px
 p { 
margin: 25px;
}

Default value

When setting the margin property to auto, value auto, it will automatically center the element horizontally. The element occupies the predetermined width, the rest will be divided equally for the left and right margins.

 div { 
width: 300px;
margin: auto;
border: 1px solid red;
}

Value inherit (inherited)

This example sets the left margin of the word section

class = 'ex1'> inherits from the parent element

 div { 
border: 1px solid red;
margin-left: 100px;
}

p.ex1 {
margin-left: inherit;
}

Collapse Margin

Sometimes the upper and lower margins of the elements overlap into a single margin equal to the size of the larger margin. This only happens with the top and bottom margins, not with the left and right margins.

 h1 { 
margin: 0 0 50px 0;
}

h2 {
margin: 20px 0 0 0;
}

In the above example, the lower margin of

 

is 50px and the upper margin of

 

is 20px. Usually the middle margin

 

and

 

will be the sum of both (i.e. 70px = 50px + 20px) but due to the alignment, this margin is only 50px.

Last lesson: Contour in CSS

The following article: Padding in CSS

5 ★ | 1 Vote