CSS margin is used to set the space between the HTML element tag border and its content. This is a single setting shorthand property to set the margin of the HTML element.
By using this property, margin from all sides can be given in a single setting.
Syntax
1 |
margin: enter value in px, em or percentage |
CSS Margin
There are 4 different value formats for the CSS margin. You can find these formats with the examples and explanations given below.
Single Value Format.
This will define the same value for all the sides. By using this you can give value for all the sides with just a single format.
1 2 3 4 5 6 7 8 9 10 11 12 |
<style> .div-margin{ border:1px solid green; } p.margin-single{ background:#ccc; margin:20px; } </style> <div class="div-margin"> <p class="margin-single">This is the HTML paragraph to show CSS margin using single value format.</p> </div> |
Output
This is the HTML paragraph to show CSS margin using single value format.
In the above example, the p tag defines the 10px margin for all the sides.
Double Value Format
This will define the two values for all the sides. The first value is for the top and bottom, the second value is for left and right. By using this you can give value for all the sides with two value formats.
1 2 3 4 5 6 7 8 9 10 11 12 |
<style> .div-margin-two{ border:1px solid green; } p.margin-two{ background:#ccc; margin:40px 60px; } </style> <div class="div-margin-two"> <p class="margin-two">This is the HTML paragraph to show CSS margin with two values</p> </div> |
Output
This is the HTML paragraph to show CSS margin with two values
Triple Value Format.
This will define the three value for all the sides. The first value is for top, the second value is for left and right, the third is for bottom. By using this you can give value for all the sides with three value format.
1 2 3 4 5 6 7 8 9 10 11 12 |
<style> .div-margin-triple{ border:1px solid green; } p.margin-triple{ background:#ccc; margin:40px 60px 20px; } </style> <div class="div-margin-triple"> <p class="margin-triple">This is the HTML paragraph to show triple value in CSS margin.</p> </div> |
Output
This is the HTML paragraph to show triple value in CSS margin.
Four Value Format
This will define the four value for all the sides. The first value is for top, second for right, third for bottom and fourth is for left. By using this you can give value for all the sides with four value format.
1 2 3 4 5 6 7 8 9 10 11 12 |
<style> .div-margin-four{ border:1px solid green; } p.margin-four{ background:#ccc; margin:10px 20px 30px 40px; } </style> <div class="div-margin-four"> <p class="margin-four">This is the HTML paragraph to show four values in CSS margin.</p> </div> |
Output
This is the HTML paragraph to show four values in CSS margin.