CSS Solid

CSS Margin

Margin sets space (left, right, top and bottom) around HTML element border.

<p style="margin:10px;">First row</p>

Example:

                        
<head>
<title> Box Model Margin  </title>
    <style>
        p {
            background-color: lightgreen;
            font-weight: bold;
            font-size: larger;
        }
    </style>
</head>
<body >
<p style="margin:10px;" >First row - margin:10px;</p>
<p style="margin:50px;">Second row - margin:50px;</p>
<p style="padding:50px;">third row - padding:50px;</p>
</body>
                     
                     

In the above code,

  • In the first para (P) element, margin 10px is applied to all sides of the element.
  • In the second para (P) element, margin 50px is applied to all sides of the element.
  • In the third para (P) element, padding 50px is applied to all sides of the element.

 

Result:

 

Margin shorthand version:

Shorthand version is used to specify multiple lines of margin properties in one line. Following example shows detailed and shorthand version.

Margin detailed version Margin shorthand version
margin-top:20px;
margin-right:10px;
margin-bottom:30px;
margin-left:15px;
 margin: 20px 10px 20px 15px  

 

Property Equal to
1
margin:20px;
margin-top:20px;
margin-right:20px;
margin-bottom:20px;
margin-left:20px;

Here margin property has only one value (20px), this value is applied to all four sides (top, right, bottom and left) of the element.

2
margin:10px 20px
margin-top:10px;
margin-right:20px;
margin-bottom:10px;
margin-left:20px;

Here margin has two values (10px 20px). First value (10px) is applied to top and bottom sides of the element. Second value (20px) is applied to right and left sides of the element.

3
margin:10px 20px 30px
margin-top:10px;
margin-right:20px;
margin-bottom:30px;
margin-left:20px;

Here margin property has three values (10px 20px 30px). First value (10px) is applied to top side of the element. Second value (20px) is applied to right and left sides of the element. Third value (30px) is applied to bottom side of the element.

4
margin:10px 20px 30px 5px
margin-top:10px;
margin-right:20px;
margin-bottom:30px;
margin-left:5px;

Here margin property has four values (10px 20px 30px). First value (10px) is applied to top side of the element. Second value (20px) is applied to right side of the element. Third value (30px) is applied to bottom side of the element. Forth value (5px) is applied to left side of the element.