In this tutorial you will learn about the CSS Margins and its application with practical example.
Margins specifies the space around the border of a HTML Element, and it specifies the spacing among the different HTML Elements. We can specify margins up to the four sides, CSS margins are specified in a same way as for borders – they can be set individually for each side, or all sides at once.
Margins on all Sides:
Example Code:
1 2 3 |
<div style="border:1px solid green;"> <p style="border:1px solid red;margin:20px;">Margin of 20 pixels on all four sides.Nested within a div with a border.</p> </div> |
Output:
Margin of 20 pixels on all four sides.Nested within a div with a border.
Margins for Individual Side
If you don’t want the margin to be applied to all four sides, or if you want each side to have different margins applied, you can use the following properties:
margin-top
margin-right
margin-bottom
margin-left
Example Code:
1 |
<p style="border:1px solid red;margin-left:20px;">This text has a left margin of 20 pixels.</p> |
Output:
This text has a left margin of 20 pixels.
Margin Property
Margin property enable us to set all four margins in one declaration. This method uses a shorthand property for setting margin-top, margin-right, margin-bottom, and margin-left in the one place. This method is fast.
It is not necessary to provide different values for all four sides. We can set one, two, three, or four values. If there is only one value, it applies to all sides. If there are two values, the top and bottom margins are set to the first value and the right and left margins are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.
Variation | Description |
---|---|
margin:10px; | All four sides have a margin of 10 pixels. |
margin:10px 20px; | Top and bottom have a margin of 10 pixels. Right and left have a margin of 20 pixels. |
margin:10px 20px 30px; | Top is 10px Left and right are 20px Bottom is 30px |
margin:10px 20px 30px 40px; | Top is 10px Right is 20px Bottom is 30px Left is 40px |