Margins

The margin property determines the margin of an element from other elements or the border of the outer container. There are special CSS properties to set padding for each side:

  • margin-top : top padding
  • margin-bottom : bottom margin
  • margin-left : left margin
  • margin-right : margin to the right

For example:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Box model in CSS3</title>
</head>

<body>
    <div>
        <p>First block</p>
    </div>
    <div>
        <p>Second block</p>
    </div>
    <div>
        <p>Third block</p>
    </div>
</body>

</html>


Instead of four properties, you can set one:

div{
    margin: 30px 20px 15px 25px;
    
    border: 3px solid red;
}

The property is set in the format:

margin: margin_top margin_right margin_bottom margin_left;
If the values for all four indents match, then we can specify only one value:

div{
    margin: 25px
}

In this case, 25 pixels will be used for all four paddings.

To set padding, you can use exact values in pixels (px) or em, or percentages, or a value auto(automatic padding).

For example:

margin-left: 2em;

The value 2 em specifies a spacing that is twice the element’s font size.

When using percentages, web browsers calculate the amount of padding based on the width of the container element that encloses the styled element.

At the same time, if several elements are in contact with us, then the browser selects the largest indent of the element, which is then used. So, in the example above, the following style was used:

div{
    margin-top: 30px; 
    margin-left: 25px;  
    margin-right: 20px;  
    margin-bottom: 15px;  
}

The distance between the first and second divs will be 30 pixels, which is the property value of the margin-top second div, even though the first div has a property margin-bottom of 15 pixels.