CSS Margin

The CSS margin property is used to create space around the HTML element border. These spaces could be of type top margin, bottom margin, left margin, right margin.

Assigning Margins for Individual Sides

CSS provides margin properties for four sides of an element.

  • margin-top
  • margin-right
  • margin-bottom
  • margin-left

All the margin properties can assign the following values:

  • auto - the browser automatically calculates the margin.
  • length - specifies a margin in px, pt, cm, etc.
  • % - specifies a margin in % of the width of the containing element ,means this concept works on the basis of relative concept.
  • inherit - It indicates that margin could be in inherited from the parent element.

Remember- The CSS Margin property is used to layout the HTML documents. Margin is basically a space generated outside of the HTML tag border.

General Syntax

     div {
  border: 1px solid black;
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
  background-color: lightblue;
}
    

Source Code

      
         div {
  border: 1px solid black;
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
  background-color: lightblue;
}      
  

Code Explanation

Note- Margin is free space outside of the border of an HTML element.

The Margin Shorthand Property

The margin property is a shorthand property to avoid setting the margin of each side separately, i.e., margin-top, margin-right, margin-bottom and margin-left.

Let's take a look at the following example to understand how it basically works.

General Syntax

     h2{ margin: 50px; /* apply to all four sides */ } 
p{ margin: 25px 75px; /* vertical | horizontal */} 
div{ margin: 25px 50px 75px; /* top | horizontal | bottom */ }
hr {margin: 25px 50px 75px 100px; /* top | right | bottom | left */ }
    

Source Code

      
         h2 { margin: 50px; /* apply to all four sides */ } 
p { margin: 25px 75px; /* vertical | horizontal */ } 
div { margin: 25px 50px 75px; /* top | horizontal | bottom */ } 
hr { margin: 25px 50px 75px 100px; /* top | right | bottom | left */ }      
  

Code Explanation

Attention!! Please keep in mind that,margin:20px is applied to the element and creates top,right,bottom,left margin upto 20px .

Online Test / Quiz

Our Tutorials

CSS Margin
Html Tutorial HTML
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4
Materialize CSS Tutorial MATERIALIZE CSS