CSS margin Property
The margin shorthand property sets the margin area on all four sides of an element outside its border.
Description & Usage
The margin property creates empty transparent space around an element, separating it from neighboring elements outside its border.
Setting margin: 0 auto on a block element with a fixed or maximum width is a classic technique for horizontally centering containers on web pages.
Adjacent vertical margins on block elements exhibit margin collapsing, where neighboring margins combine into a single margin equal to the larger of the two values.
Property Specifications
| Property Feature | Specification |
|---|---|
| Category | Box Model |
| Initial Value | 0 |
| Inherited | No (not inherited) |
| Applies To | All elements except table display types |
Syntax
margin: 10px | 10px 20px | 10px 20px 30px 40px | auto;Property Values
| Value | Description |
|---|---|
| 10px | Applies 10px margin to top, right, bottom, and left sides. |
| 10px 20px | 10px top/bottom, 20px left/right. |
| 0 auto | Horizontally centers a fixed-width block element inside its parent. |
Code Examples
Horizontal Page Centering
.main-container {
max-width: 1200px;
margin: 0 auto;
}
Centers block container horizontally on large screens.