【问题标题】:What's the difference between margin:auto and justify-content / align-items center?margin:auto 和 justify-content / align-items center 有什么区别?
【发布时间】:2017-10-29 21:13:28
【问题描述】:

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

第一

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

第二

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

有什么区别?在什么情况下我们会使用其中一种?

【问题讨论】:

  • 两种解决方案的作用相同。这里缺少的是到 .outer 的高度,例如 height:100vh;

标签: html css flexbox centering


【解决方案1】:

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

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

...auto 边距仅适用于弹性项目,并在容器中居中该弹性项目。

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

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

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

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

8.1. Aligning with auto margins

在通过justify-contentalign-self 对齐之前,任何 正的可用空间分配到该维度的自动边距

如果空闲空间分配给自动边距,对齐属性 将在该维度上没有影响,因为边距将有 偷走了弯曲后剩余的所有可用空间。

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

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

这里有一个更完整的解释:

IE 错误:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-16
    • 2018-07-10
    • 2016-05-05
    • 2022-12-11
    • 2017-04-06
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多