margin:auto 和 justify-content/align-items center 之间有什么区别? [英] What's the difference between margin:auto and justify-content / align-items center?
问题描述
要同时水平和垂直居中,有两个简单的选项:
To center both horizontally and vertically simultaneously, there are two simple options:
第一次
.outer {
display:flex;
}
.inner {
margin:auto;
}
第二个
.outer {
display: flex;
justify-content: center;
align-items: center;
}
有什么区别?在什么情况下我们会使用其中一种?
What's the difference? In what situations would we use one over the other?
推荐答案
在你的第一个例子中...
In your first example...
.outer {
display: flex;
}
.inner {
margin: auto;
}
... auto
边距仅适用于 flex 项,并在容器中居中该 flex 项.
... 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.
另外,请记住,如果您同时使用这两种方法,margin: auto
应该占上风.
Also, keep in mind, if you use both methods at the same time, margin: auto
should prevail.
在通过 justify-content
和 align-self
对齐之前,任何正自由空间分配到该维度的自动边距
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.
要克服这个问题,请使用 margin: auto
进行居中以正常工作.
To overcome this problem, use margin: auto
for centering to work properly.
这里有一个更完整的解释:
Here's a more complete explanation:
- 无法滚动到容器溢出的弹性项目的顶部
- 垂直和水平居中一个 flex 项目(见方框 #56)
- Can't scroll to top of flex item that is overflowing container
- Center a flex item vertically and horizontally (see Box #56)
IE 错误:
这篇关于margin:auto 和 justify-content/align-items center 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!