Auto margin

2 snippets in HTML & CSS

Also written as margin auto

HCHTML & CSS

Margin

HC · Box Model
Syntax
margin: top right bottom left;
margin: vertical horizontal;
margin: all;
Example
.section {
  margin: 40px 0;
}

.container {
  margin: 0 auto; /* center horizontally */
  max-width: 1200px;
}

.spaced-item {
  margin-top: 16px;
  margin-bottom: 16px;
}

Note Vertical margins collapse: when two vertical margins touch, only the larger one applies (not their sum). Margins on flex and grid children do not collapse. Use margin: 0 auto on a block element with a set width to center it.

Flex Spacer Pattern (Push Items Apart)

HC · Flexbox
Syntax
margin-left: auto; /* or margin-right: auto */
Example
/* Push the last item to the far right */
.navbar {
  display: flex;
  align-items: center;
  gap: 16px;
}

.navbar .user-menu {
  margin-left: auto;
}

Note Auto margins in flexbox consume all available space in that direction. This pushes elements apart without justify-content: space-between, which is useful when you need only one item pushed to the end.

Frequently asked questions

How does HTML & CSS handle auto margin?
HTML & CSS covers this with 2 copy-ready snippets on this page. The "Margin" snippet in HTML & CSS uses `margin: top right bottom left;`.
Which code does the HTML & CSS example use?
The "Margin" snippet uses `margin: top right bottom left;`, from the Box Model section of the HTML & CSS cheat sheet.
What other HTML & CSS snippets are shown for "auto margin"?
Besides "Margin", this page also shows "Flex Spacer Pattern (Push Items Apart)".
Is there anything to watch out for?
Yes. For "Margin": Vertical margins collapse: when two vertical margins touch, only the larger one applies (not their sum). Margins on flex and grid children do not collapse. Use margin: 0 auto on a block element with a set width to center it.