In this section, we will learn what the margin property is and how to use it in CSS.
Click here to run the example of margin property.
CSS margin Property Definition and Usage
Consider two elements sitting next to each other; by default, there’s a small gap in between these two elements. This is what we call margin. As the picture above shows, by default, margins exist all around an element and sit right after its border.
CSS provided a property named `margin` by which we can control the width of margins around an element.
Basically, the margin property is a shorthand one for the following properties:
- margin-top: this property is used to set the top margin of an element.
- margin-right: this property is used to set the right margin of an element.
- margin-bottom: this property is used to set the bottom margin of an element.
- margin-left: this property is used to set the left margin of an element.
So by using the `margin` property, we can set the values for the mentioned properties in one declaration.
Note: there are more into the CSS margin which you can learn about it in the CSS margin Section.
CSS margin Property Syntax
margin: length|auto|initial|inherit;
margin: value1 value2 value3 value4
When we set 4 values for the margin property, the first value specifies the top margin. The second value specifies the right margin, the third value specifies the bottom margin, and the last value specifies the left margin.
margin: value1 value2 value3
When we set 3 values for the margin property: the first value specifies the top margin, the second value specifies the right and left margins, and the third value specifies the bottom margin of the target element.
margin: value1 value2
When we set 2 values for the margin property, the first value specifies the top and bottom margin and the second value specifies the left and right margins of the target element.
margin: value
When we set only one value for this property, the entire margins of an element will be set to the same value.
CSS margin Property Value
The value of this property is a number with relative and absolute units supported in CSS.
Note: you could also use the two global values “initial” and “inherit” for this property.
Example: margin in CSS
See the Pen margin in CSS by Omid Dehghan (@enjoytutorials1) on CodePen.
Margin Auto in CSS
We can use the value “auto” for the margin property as well. In that case, the target element becomes horizontally centered in its container element.
Example: margin auto in CSS
See the Pen margin auto in CSS by Omid Dehghan (@enjoytutorials1) on CodePen.