Free Web Development Online Tutorials, Learn to Code
html a css margin, css margin color, css margin property, margins css

CSS Margin Property Style

As a web designer, our job is to make the webpage attractive and responsive for different device, and to make that we often need to set margin of html element to maintain the space around that element, here we learn how to set margin of html element using CSS style, html element like html div, span, p, table etc.

CSS margin property indicates the space around an HTML element. We can use negative values to overlap content, means margin can be less than zero

How to define Margin in CSS

Below is the example of how we can define margin of any html element, we can set different margin for each side as shown in code.

<style>
.div{
    margin-top:10px;
    margin-top:5px;
    margin-left:4px;
    margin-right:6px;
    }
    </style>

Any margin property can have the following values:

  • % - indicate margin in % of the width of container
  • length - specifies a fix margin in px, pt, cm, etc.

Margin can be set for each side as shown in above example, but if you don’t specify any side then margin will be applied to all the side like below example

<style>
.div{
        margin:10px;
}
</style>

Above style indicates 10px margin for each side of div.

You also can define margin of all sides like margin: 4px 2px 7px 4px;

Different side of margin

  • margin-top

    indicates the top margin of an html element

    .M1 {
        margin-top:10px;
    }
    
  • margin-bottom

    indicates the bottom margin of an html element

    .M1 {
        margin-bottom: 10px;
    }
    
  • margin-left

    indicates the left margin of an html element

    .M1 {
        margin-left: 5px;
    }
    
  • margin-right

    indicates the right margin of an html element

    .M1 {
        margin-right: 5px;
    }
    

Margin Auto Example

Margin auto 0 will keep any div in centre of html page, this is very useful when you want to keep the layout in center of the screen.

<div style="width:50%;margin: 0 auto;">
            
</div>
CSS Style Examples