margin:auto 和 justify-content / align-items center 有什么区别?

What's the difference between margin:auto and justify-content / align-items center?

要同时水平和垂直居中,有两个简单的选项:

第一个

.outer {
  display:flex;
}
.inner {
  margin:auto;
}

第二

.outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

有什么区别?在什么情况下我们会使用一个而不是另一个?

在你的第一个例子中...

.outer {
  display: flex;
}
.inner {
  margin: auto;
}

... auto 边距仅适用于 flex 项目并使容器中的一个 flex 项目居中。

在你的第二个例子中...

.outer {
  display: flex;
  justify-content: center;
  align-items: center;
}

您正在使容器级别的项目居中。此代码将使 所有 项居中。

此外,请记住,如果您同时使用这两种方法,margin: auto should 为准。

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.

但最重要的区别,出于实际目的,可能是弹性项目超过容器大小时的行为。发生这种情况时,您将无法在使用容器级代码时访问项目的某些部分。该项目从屏幕上消失,无法通过滚动访问。

要解决此问题,请使用 margin: auto 居中以正常工作。

这里有更完整的解释:

  • (见方框#56)

IE 漏洞:

  • Flex auto margin not working in IE10/11