CSS Margin
The CSS margin property defines space around elements, remaining transparent without any background color. It clears an area around the element.
CSS Margin Properties
There are specific properties that allow you to manipulate margins individually:
- margin: Sets all properties in one declaration.
- margin-left: Sets the left margin of an element.
- margin-right: Sets the right margin of an element.
- margin-top: Sets the top margin of an element.
- margin-bottom: Sets the bottom margin of an element.
CSS Margin Values
These are the potential values for the margin property:
- auto: Allows the browser to calculate a margin.
- length: Specifies a margin in pixels, points, centimeters, etc. The default value is 0px.
- %: Defines a margin in percent of the width of the containing element.
- inherit: Inherits the margin from the parent element.
Note: Negative values can be used to overlap content.
CSS Margin Example
Demonstrating different margins for different sides of an element:
Margin: Shorthand Property
The shorthand property enables concise coding. There are different ways to specify the margin property:
- margin: 50px 100px 150px 200px;
- Top margin: 50px
- Right margin: 100px
- Bottom margin: 150px
- Left margin: 200px
- margin: 50px 100px 150px;
- Top margin: 50px
- Left and right margin: 100px
- Bottom margin: 150px
- margin: 50px 100px;
- Top and bottom margins: 50px
- Left and right margins: 100px
- margin: 50px;
- Top, right, bottom, and left margins: 50px
Utilize these shorthand methods to set margins efficiently in your code.