margin
Sets the outer space between an element and its neighbors.
- Initial value
0- Inherited
- No
- Animatable
- yes, as a length
- Applies to
- all elements except internal table elements
- JavaScript
element.style.margin = "16px auto"
Example
#.page {
max-width: 420px;
margin: 0 auto;
}
.page h2 {
margin-bottom: 8px;
}<div class="page stage">
<h2 style="margin-top: 0">A centered page</h2>
<p style="margin: 0">A block with a 420px max width sits in the center thanks to margin: 0 auto.</p>
</div>Definition and usage
#The margin property is shorthand for four margins: margin-top, margin-right, margin-bottom, and margin-left. A margin is transparent space outside the border that pushes an element away from others.
One value sets all four sides, two set the vertical and horizontal sides separately, three set the top, the horizontal sides, and the bottom, and four set the top, right, bottom, and left in turn (clockwise). A horizontal auto centers a block that has a defined width.
Watch out for margin collapsing: the vertical margins of adjacent blocks don’t add up, the larger one simply wins. This doesn’t happen inside flex or grid containers.
Syntax
#margin: <top> <right>? <bottom>? <left>?;Values
#- No margin. The parent’s background stripes sit right up against the element.
<length>
An equal 16px margin on every side.vertical horizontal
8px on top and bottom, 40px on the sides.auto
A horizontalautocenters a block that has a known width.negative value
A negative margin pulls the element closer, or even pushes it outside its parent.
Values in practice
#0
.demo { margin: 0; }16px
.demo { margin: 16px; }8px 40px
.demo { margin: 8px 40px; }12px auto
auto centers a block that has a known width..demo { margin: 12px auto; }-8px
.demo { margin: -8px; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Use
gapfor spacing between items in a row or grid, not margins. - The logical properties
margin-inlineandmargin-blockalso work correctly in right-to-left languages.
Related entries
#- margin vs paddingmargin is transparent space outside the element. padding is space inside the border, between the content and the edge, and it takes on the element’s background.
- paddingSets the inner space between the content and the border.
- borderShorthand that sets the width, style, and color of a border.
- gapSets the spacing between items in a flex, grid, or multi-column container.
- box-sizingDecides whether width and height include the padding and border.
- margin-inlineSets the margins at the start and end of a line. The logical version of margin-left and margin-right, aware of writing direction.
Spotted a mistake or missing an example? Write to us.