在 `flex-grow: 1` 内垂直居中

rra*_*rag 6 css 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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

我使用以下方法在页面底部实现了粘性页脚,flex-grow但这会导致内容高度未知

如何将某物置于 的中间content?是否可以使用 Flexbox 或者可以是替代方法?

Obs*_*Age 5

你的想法几乎完全正确!.foo您无需在( display: flex;justify-content: center; 和)上设置垂直居中规则align-items: center;,而只需在父级上设置它们.content

如下所示(单击Run snippet,然后Full page查看效果):

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这也可以在 CodePen 上看到。