CSS: margin
This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文
Set the 4 Margins of an Element
Definition and Usage
The margin shorthand property sets all margin properties in a single declaration. This property can have 1 to 4 values.
Description
This shorthand property sets the width of all margins on an element, or the margin width on each side.
Adjacent vertical margins of block-level elements collapse, while top and bottom margins do not affect the layout of inline elements. The left and right margins of inline elements do not collapse. Likewise, margins of floated elements do not collapse. Negative margin values are allowed, but use them with caution.
Note: Negative values are allowed.
Example 1
margin:10px 5px 15px 20px;
- The top margin is 10px
- The right margin is 5px
- The bottom margin is 15px
- The left margin is 20px
Example 2
margin:10px 5px 15px;
- The top margin is 10px
- The right and left margins are 5px
- The bottom margin is 15px
Example 3
margin:10px 5px;
- The top and bottom margins are 10px
- The right and left margins are 5px
Example 4
margin:10px;
- All 4 margins are 10px
Property Value Default value: 0 Inherited: no Version: CSS1 JavaScript syntax: object.style.margin="10px 5px"
Possible Values
| Value | Description |
|---|---|
| auto | The browser calculates the margin. |
| length | Specifies the margin in units such as pixels or centimeters. The default value is 0px. |
| % | Specifies the margin as a percentage of the containing element's width. |
| inherit | Specifies that the margin should be inherited from the parent element. |
TIY Examples
All margin properties in a single declaration
This example demonstrates how to set all margin properties in a single declaration.
Related Pages
CSS tutorial: CSS Margins
HTML DOM reference: margin Property
Last updated 2024-01-14
Comments 0