CSS margin properties enable the creation of space around elements, independent of any defined borders.
With CSS, you possess complete authority over margins. Various properties allow you to set margins for individual sides of an element, including top, right, bottom, and left.
CSS features properties to designate the margin for every side of an element.
The following values can be assigned to all margin properties:
Here are the possible values for all margin properties:
Tip: Negative values are permissible.
Example
Assign distinct margins to each of the four sides of a <p> element.
p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 80px; } |
To condense the code, you can specify all margin properties using a single shorthand property.
The margin property serves as a shorthand for the following individual margin properties:
Here’s how it functions:
If the margin property contains four values:
Example
Use the margin shorthand property with four specified values.
p { margin: 25px 50px 75px 100px; } |
If the margin property is set using three values.
Example
Apply the margin shorthand property with three values.
p { margin: 25px 50px 75px; } |
If the margin property is set with two values.
Example
Apply the margin shorthand property with two values.
p { margin: 25px 50px; } |
If the margin property is set with one value.
Example
Apply the margin shorthand property with a single value.
p { margin: 25px; } |
You can set the margin property to auto to center the element horizontally within its container. This will make the element occupy the specified width, with the remaining space evenly distributed between the left and right margins.
Example
Use margin: auto:
div { width: 300px; margin: auto; border: 1px solid red; } |
This example allows the left margin of the <p class=”ex1″> element to be inherited from its parent element (<div>):
Example
Using the inherit value:
div { border: 1px solid red; margin-left: 100px; } p.ex1 { margin-left: inherit; } |
Property |
Description |
margin |
A single declaration shorthand for configuring all margin properties. |
margin-bottom |
Specifies the margin at the bottom of an element. |
margin-left |
Specifies the margin on the left side of an element. |
margin-right |
Specifies the margin on the right side of an element. |
margin-top |
Specifies the margin at the top of an element. |