CSS Margin
The CSS margin property is used to create space around elements, outside of any defined borders. It helps in controlling the distance between an element's border and adjacent elements. Proper use of margins allows for clean, well-structured layouts.
Key Points on CSS Margin:
- The
margin
property can be set using values fortop
,right
,bottom
, andleft
sides. - Margin values can be specified in
px
,em
,%
, and other units. - If only one value is provided, it will apply to all four sides.
- Two values specify
top/bottom
andleft/right
margins. - Three values specify
top
,left/right
, andbottom
. - Negative margins are allowed, which can pull elements closer together.
- Margins collapse when two adjacent vertical margins meet, i.e., the larger value is used.
Syntax for CSS Margin:
Syntax Example
/* Margin shorthand syntax */
margin: top right bottom left;
/* Example */
margin: 20px 15px 10px 5px;
Examples of CSS Margin:
The following examples demonstrate the usage of different margin properties:
Code Example: Margin with Single Value
div {
margin: 20px;
}
Output
This div has a margin of 20px on all sides.
Code Example: Margin with Two Values
div {
margin: 20px 15px;
}
Output
This div has 20px margin on top and bottom, and 15px margin on left and right.
Code Example: Margin with Negative Values
div {
margin: -10px;
}
Output
This div has a negative margin of -10px.
Common Margin Properties:
- margin-top: Sets the margin on the top of the element.
- margin-right: Sets the margin on the right of the element.
- margin-bottom: Sets the margin on the bottom of the element.
- margin-left: Sets the margin on the left of the element.
- margin: Shorthand property that sets all four margins at once.
Using margins effectively helps in creating space between elements and making layouts more visually appealing. Ensure consistency in margin use to maintain a uniform design.