What's the difference between margin: auto and align-content / align items?
To center both horizontally and vertically at the same time, there are two simple options:
The first
.outer {
display:flex;
}
.inner {
margin:auto;
}
Second
.outer {
display: flex;
justify-content: center;
align-items: center;
}
Who cares? In what situations will we use one over the other?
source to share
In the first example ...
.outer {
display: flex;
}
.inner {
margin: auto;
}
... the marker auto
applies only to the flex item and centers that one flex item in the container.
In your second example ...
.outer {
display: flex;
justify-content: center;
align-items: center;
}
You center the elements from the container level. This code will center all elements.
Also, keep in mind that if you are using both methods at the same time, margin: auto
should prevail.
Before aligning through
justify-content
andalign-self
, any positive white space is propagated to the automatic margins at that sizeIf the free space extends to automatic margins, then the alignment properties will have no effect in that dimension, since the margins will have stolen all of the free space after folding.
But the most important difference for practical purposes may be the behavior when the flex item exceeds the container size. When this happens, you lose access to parts of the element when using container-level code. The item disappears from the screen and is not available by scrolling.
To fix this problem, use the margin: auto
center to work properly.
Here's a more complete explanation:
- Unable to scroll to the top of flex item that overflows container
- Center the slender vertically and horizontally (see box 56).
IE Errors:
source to share