The CSS Margin
The CSS margin element is used to place spacing outside of an element. Typically used to set spacing between div's and images. There are several different ways you can set the margin value.
- Percentages - %
- Centimeters - cm
- Pixels - px
The four sides can be specified independently. This gives you the ability to assign just one setting for a specific element or multiple elements.
Example of the CSS margin properties;
- margin-top:5px;
- margin-right:5px;
- margin-bottom:5px;
- margin-left:5px;
Don't worry, you don't have to set your margins this lengthy way. There are short cuts available we can use to accomplish the same thing.
CSS Margin Shortcuts
With the above, the four sides of the margin setting are set to be 5 pixels each. This can be shortened down to
margin:5px;
Simple enough. Now say you want to have the top and bottom margins set to 5px and the two sides set at 20px. You don't have to use the longer version
Shorthand your settings;
margin:5px 20px;
The first decaration sets the top and bottom, the second declaration sets the two sides.
Additional shorthand for the CSS margin
You can control the four sides independantly in a single margin declaration by simply adding the additional declarations.
margin:5px 10px 15px 20px;
In this case the margins are controlled in a clockwise direction starting with the top.
- The top is set at 5px
- The right is set at 10px
- The bottom is set at 15px
- The left is set at 20px
The CSS margin can also be used to set a negative value. This allows you to use it to create overlapping elements.
margin:-10px;
Use the editor to play around with different margin settings. I have started it out with the second pargraph having all four sides set at 20px.