CSS Margins

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

Assigning Margins for Individual Sides

CSS provides margin properties for four sides of an element.These are : 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, which means this concept works on the basis of a relative concept.
  • inherit - It indicates that the margin could be 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.

Source Code

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

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

      h1 {
  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 */
}
    
Try it now

Source Code

          .main_text_content{
  margin: 20px;
  background-color: green;
  color: white;
  padding: 10px;
  font-size: 17px;
}
        
Try it now

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

Web Tutorials

CSS Margins
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4