In your first example...
.outer {
display: flex;
}
.inner {
margin: auto;
}
... the auto
margin applies only to the flex item and centers that one flex item within the container.
In your second example...
.outer {
display: flex;
justify-content: center;
align-items: center;
}
You are centering items from the container level. This code will center all items.
Also, keep in mind, if you use both methods at the same time, margin: auto
should prevail.
8.1. Aligning with auto
margins
Prior to alignment via justify-content
and align-self
, any
positive free space is distributed to auto margins in that dimension
If free space is distributed to auto margins, the alignment properties
will have no effect in that dimension because the margins will have
stolen all the free space left over after flexing.
But the most important difference, for practical purposes, may be the behavior when a flex item exceeds the size of the container. When this happens, you lose access to parts of the item when using the container-level code. The item disappears from the screen and is not accessible via scroll.
To overcome this problem, use margin: auto
for centering to work properly.
Here's a more complete explanation:
IE Bugs:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…