CSS Properties
Margin
The CSS property margin can be used to create space around an
element's border and its surrounding elements. The value of this
property can be specified using any of the length unit specification
alternatives we discussed in a previous
lesson.
Code example: shorthand
.lonely-box {margin: 1em; /* equivalent */margin: 1em 1em; /* equivalent */margin: 1em 1em 1em 1em; /* equivalent */border: 1px solid black;}
which produces
The div below me has 1em margin on all sides. That's why I am so far away..lonely-boxThe div above me has 1em margin on all sides. That's why I am so far away.
Notice how there is a 1em distance between the the border and the
two other paragraphs on the top and bottom sides.
Code example: extended
.lonely-box {margin-top: 1em;margin-right: 1em;margin-bottom: 1em;margin-left: 1em;border: 1px solid black;}
This .lonely-box class and the previous one accomplish the exact
same style. Which one we choose is up to us, though most developers
tend to prefer the shorthand version.
Code example: centering
.centered {width: 512px;margin: 0 auto;}
We can center elements horizontally within its parent element by
explicitly specifying a width and setting the right and left margins
to auto.
I am horizontally centered within my green parent element.
Read more on MDN
margin
Test yourself
Description
Add 0.5em margin on the top side to the .quote footer element in
order to create some spacing between the actual quote text and the
author.
All relevant rules have been defined for you. Add declarations where appropriate. Whether you want use the shorthand or extended notation is up to you.
Tests
- 1
Your
.quote footerelement should have a top margin of0.5em. - 2
Your
.quote footerelement should have a right margin of0. - 3
Your
.quote footerelement should have a bottom margin of0. - 4
Your
.quote footerelement should have a left margin of0.