Contents
Adding CSS margins
The CSS margin
property allows you to add extra space around the chosen element:
Providing sufficient spacing around menu items, scrollbars, and other HTML elements clarifies and improves the overall structure of the page. Thus, CSS margins make it easier for the user to navigate and interact.
Note: don't get confused with CSS
margin
vspadding
:margin
sets the spacing outside the borders, and padding does so within the element.
Setting CSS margin values
When using the CSS margin
property, you can define up to four values:
margin: value1 value2 value3 value4;
Based on how many values you specify, the property assumes the remaining values using different logic. Understand how to define the CSS margin order by reviewing the table below.
Syntax | Example | Explanation |
---|---|---|
One value | margin: 5px; | All four margins are the same. |
Two values | margin: 5px 10px; | The first value defines the top and bottom margins. The second value defines the left and right margins. |
Three values | margin: 5px 10px 15px; | The first value defines the top margin. The second value defines the left and right margins. The third value defines the bottom margin. |
Four values | margin: 5px 10px 15px 20px; | The first value defines the top margin. The second value defines the right margin. The third value defines the bottom margin. The fourth value defines the left margin. |
You can define the width for CSS margin
in either length units (e.g., pixels) or percentages (in relation with the container block). The default value is 0 0 0 0
, which represents no CSS margin.
Tip: you can also use the keyword
auto
, in which case the browser will select the margin for the HTML element.
Manipulating each CSS margin individually
CSS margin
is actually a shorthand for four subproperties:
margin-top
margin-right
margin-bottom
margin-left
If you don't want to use the shorthand or just want to be extra sure about the CSS margin order, you can also use the subproperties on their own.
To apply margin to the top of an element, use margin-top
:
To apply margin to the right of an element, use margin-right
:
To apply margin to the bottom of an element, use margin-bottom
:
To apply margin to the left of an element, use margin-left
: