为什么我的容器不是垂直和水平对齐的中心

时间:2014-07-24 12:30:49

标签: html css css3 flexbox

为什么我的容器不能垂直和水平对齐。

<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

2 个答案:

答案 0 :(得分:3)

水平对齐是justify-content: center

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

  1. 将所有父元素声明为100%高度。这是<body style="height:100%"> <html style="height:100%">。否则它只是父元素的100%,它只具有适合所有内容的所需大小。
  2. 设置弹性容器fixedabsolute
  3. 的位置

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

答案 1 :(得分:0)

因为你没有声明它。在元素中添加以下内容:

.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);
}

为此,您需要了解width的{​​{1}}和height

修改

好的,我得到了.flex-container解决方案的downvote。与其他用户一起改进可能和正确的解决方案,而不是改进我的答案。感谢。

您还可以将position: absolute;添加到margin: auto;,但之后需要设置固定的.flex-container。这将使您的元素水平居中。但不是垂直的。为此,您仍需要应用widthposition: absolute;