【问题标题】:Why is my container not center aligned vertically and horizontally为什么我的容器没有垂直和水平居中对齐
【发布时间】:2014-07-24 20:48:06
【问题描述】:

为什么我的容器没有垂直和水平居中对齐。

<div class="flex-container">
  <header></header>
  <article></article>
  <aside></aside>
  <footer></footer>
</div>

CSS

.flex-container {
  display: flex;
  flex-flow: row;
  align-items: center;
  justify-center: center;
}

.flex-container > * {
  min-width: 100px;
  min-height: 100px;
}

header {
  background: rgba(200, 200, 200, 1);
}

article {
  background: rgba(200, 200, 200, .8);
}

aside {
  background: rgba(200, 200, 200, .6);
}

footer {
  background: rgba(200, 200, 200, .4);
}

下面是相同的小提琴。 http://codepen.io/anon/pen/bAayc

【问题讨论】:

  • 你做了什么使它居中?
  • @Paulie_D:你看到我的代码笔了吗……上面写着 algin-items 和 justify-center to center。
  • 对齐内容...您仍然需要将容器居中。
  • 应该对齐-center: center;不做这份工作....
  • 容器为 100% 宽且居中。

标签: html css flexbox


【解决方案1】:

水平对齐是justify-content: center

对于垂直居中对齐,您有两种可能:

  1. 将所有父元素声明为 100% 高度。那是&lt;body style="height:100%"&gt; &lt;html style="height:100%"&gt;。否则,它只是 100% 的父元素,其大小正好适合所有内容。
  2. 设置弹性容器的位置fixedabsolute

 

.flex-container {
  display: flex;
  flex-flow: row;
  align-items: center;
  justify-content: center;
  height:100%;
  width:100%;
  position:absolute;
}

【讨论】:

  • 为什么我们需要100%查看父母的身高和宽度?
【解决方案2】:

因为你没有声明它。将以下内容添加到您的元素中:

.flex-container {
  display: flex;
  flex-flow: row;
  align-items: center;
  justify-center: center;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

请记住,transform 属性在 IE8 中不起作用。为此,您需要在 IE8 中添加负数 margin 而不是 translate

IE8 后备:

.flex-container {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -(HEIGHT-OF-ELEMENT);
  margin-left: -(WIDTH-OF-ELEMENT);
}

为此,您需要知道您的.flex-containerwidthheight

编辑:

好的,我的position: absolute; 解决方案投了反对票。其他用户不要对可能且正确的解决方案投反对票,而只是改进我的答案。谢谢。

您也可以将margin: auto; 添加到您的.flex-container,但您需要设置一个固定的width。这将使您的元素水平居中。但不是垂直的。为此,您仍然需要申请 position: absolute;position: relative;

【讨论】:

  • 绝对位置?真的吗?他可以用margin auto将其居中。
  • @Paulie_D true 但是对于自动边距,OP 还必须设置 flex-container 的宽度。
  • @Paulie_D 是的。他希望它水平和垂直居中。 margin: auto; 仅适用于水平中心。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 2016-09-15
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多