The following CSS margin codes demonstrate the various CSS properties you can use to apply styles to the border of any HTML element.
Margins define the space around the element. CSS margins are specified in a similar way to borders - they can be set individually for each side, or all sides at once.
Setting Margins on all Sides
<div style="border:1px solid blue;">
<p style="border:1px solid orange;margin:20px;">
This text has a margin of 20 pixels on all four sides.
It is nested within a div with a border to make it easier to see the effect of the margin.
</p>
</div>
This text has a margin of 20 pixels on all four sides. It is nested within a div with a border to make it easier to see the effect of the margin.
Setting Margins for Each Side
If you don't want the margin settings to be applied to all four sides, or if you want each side to have different margins applied, you can use the following properties:Example:
<p style="border:1px solid orange;margin-left:60px;">This text has a left margin of 60 pixels.</p>
This text has a left margin of 60 pixels.
Shorthand Property
This method uses a shorthand property for settingmargin-top
, margin-right
, margin-bottom
, and margin-left
in the one place. This method is quicker. It also uses less code than the previous method. Actually, it's the same property that we used in our first example (i.e. the margin
property). The only difference is that we apply multiple values against it.Code:
<div style="border:1px solid blue;width:200px;">
<p style="border:1px solid orange;margin:40px 10px 1px 40px;">
This text has a different sized margin for each side.
It is nested within a div with a border to make it easier to see the effect of the margin.
</p>
</div>
This text has a different sized margin for each side. It is nested within a div with a border to make it easier to see the effect of the margin.
Variations
You don't need to provide different values for all four sides. You can provide one, two, three, or four values. Here's how it works: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.
In other words:
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
No comments:
Post a Comment