- Specific margin properties
marginwith different values
- Values accepted
autoto center elements
margin CSS property is commonly used in CSS to add space around an element.
marginadds space around an element border
paddingadds space inside an element border
Specific margin properties
margin has 4 related properties that alter the margin of a single margin at once:
The usage of those is very simple and cannot be confused, for example:
margin-left: 30px; margin-right: 3em;
margin with different values
margin is a shorthand to specify multiple margins at the same time, and depending on the number of values entered, it behaves differently.
Using a single value applies that to all the margins: top, right, bottom, left.
Using 2 values applies the first to bottom & top, and the second to left & right.
margin: 20px 10px;
Using 3 values applies the first to top, the second to left & right, the third to bottom.
margin: 20px 10px 30px;
Using 4 values applies the first to top, the second to right, the third to bottom, the fourth to left.
margin: 20px 10px 5px 0px;
So, the order is top-right-bottom-left.
margin accepts values expressed in any kind of length unit, the most common ones are px, em, rem, but many others exist.
It also accepts percentage values, and the special value
auto to center elements
auto can be used to tell the browser to select automatically a margin, and it’s most commonly used to center an element in this way:
margin: 0 auto;
As said above, using 2 values applies the first to bottom & top, and the second to left & right.
The modern way to center elements is to use Flexbox, and its
justify-content: center; directive.
Older browsers of course do not implement Flexbox, and if you need to support them
margin: 0 auto; is still a good choice.