The CSS margin property is used to make space around the HTML element. In other words, CSS margin property defines the gap around HTML elements. It is possible to define a negative value to overlap content.

The values of the margin property are not inherited by the child elements. Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so that the distance between the blocks is not the sum of the margins, but only the greater of the two margins or the same size as one margin if both are equal.

We have the following properties to set an element margin.

  • The margin specifies a shorthand property for setting the margin properties in one declaration.
  • The margin-bottom specifies the bottom margin of an element.
  • The margin-top specifies the top margin of an element.
  • The margin-left specifies the left margin of an element.
  • The margin-right specifies the right margin of an element.

Now, we will see how to use these properties with examples.

CSS Margin Property

Table of Contents

The margin property allows you to set all of the properties for the four margins in one declaration. Here is the syntax to set margin around a paragraph and we will see another four sub-type of margin in this example −

Here is an example −

<html>
   <head>
<title>
Margin Property
</title>
<style>
#all{
    margin:30px;   
}
#Top{
   margin-top:10px;
}
#Bottom{
    margin-bottom:10px;
}
#Left{
margin-left:30px;}
#Right{margin-right:30px;}
p{border:solid red 1px;}
</style>
   </head>
      <body>
      <p id="all">
         all four margins will be 15px
      </p>
      
<p id="Top">Top will be 10px.</p>
<p id="Bottom">Bottom margin will be 10px </p>
<p id="Left">Left margin will be 10px</p>
<p id="Right">Right margin will be 10px</p>
   </body>
</html> 

It will produce following result.

CSS Margin Property

Share post

Leave a Reply