垂直居中于`flex-grow:1`

时间:2018-03-22 03:15:23

标签: css css3 flexbox

说我有HTML作为

<div class="page">
  <div class="header"></div>
  <div class="content">
    <div class="foo">
      <div>I want to be center of content</div>
    </div>
  </div>
  <div class="footer"></div>
</div>

CSS

html, body {
  height: 100%;
}
body {
  margin: 0;
}

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header {
  flex-shrink: 0;
  background-color: green;
  height: 50px;
}
.content {
  flex-grow: 1;
}
.footer {
  flex-shrink: 0;
  background-color: steelblue;
  height: 150px;
}

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

https://codepen.io/rrag/pen/PRmOYe

我在页面底部实现了粘性页脚 使用flex-grow但导致内容高度未知

如何在content的中间居中? 是否可以使用flexbox或者可能是另一种方法?

1 个答案:

答案 0 :(得分:1)

你几乎有正确的想法!您不必在.foodisplay: flex;justify-content: center;和align-items: center;)上设置垂直居中规则,而只需在父.content上设置它们。

可以在以下内容中看到这一点(点击Run snippet然后点击Full page即可看到此效果):

&#13;
&#13;
html,
body {
  height: 100%;
}

body {
  margin: 0;
}

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  flex-shrink: 0;
  background-color: green;
  height: 50px;
}

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

.footer {
  flex-shrink: 0;
  background-color: steelblue;
  height: 150px;
}
&#13;
<div class="page">
  <div class="header"></div>
  <div class="content">
    <div class="foo">
      <div>I want to be center of content</div>
    </div>
  </div>
  <div class="footer"></div>
</div>
&#13;
&#13;
&#13;

这也可以看作 on CodePen