带有 flex 的中间元素垂直居中

Vertical center on middle element with flex

我对居中元素有非常具体的要求,所以我决定尝试 flexbox。

请求如下。我有 3 个垂直堆叠的元素。

页眉、内容和页脚。

一个特殊的条件是中间元素 "content" 在页面(垂直和水平)上居中,页眉和页脚从上到下贴在上面。它应该与 window 调整大小一起使用。 有硬编码的解决方案可以更好地演示。 http://codepen.io/anon/pen/oXjVmE

我试图用 flex box 解决这个问题,但我得到的只是所有 3 个元素都居中。

我正在寻找如何分辨 flex-box "First and last element should be same and max possible height" http://codepen.io/anon/pen/GJpeYY

html

<div class="wrapper">
  <div class="header">
    <h1>Header</h1>
    <h2>Subheader</h2>
    <p>Text</p>
  </div>
  <div class="centered">
    Centered Text
  </div>
  <div class="footer">
    Some tiny footer
  </div>
</div>

css

.wrapper {
  height:500px;
  background-color:lightgreen;
  .display(flex);
  .flex-direction(column);
  .align-items(center);
  .justify-content(center);
  text-align: center;
}

.header {
   background-color:gold;
}

.centered {
  height: 50px;
  line-height: 50px;
  background-color:deepskyblue;
}

.footer {
  background-color:tomato;
}

删除包装器 height:500px; 并添加 height:100vh;

这是视口高度,希望你能得到你想要的。

您只需使用 flex: inline-flex 并添加一个外部容器即可实现该结果,如下面的

running demo

我已将居中的文本内容设置为可编辑,因此对其进行编辑并看到页眉和页脚随之伸展。

.container {
  text-align: center;
  background-color: lightgreen;
}
.wrapper {
  height: 500px;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
}
.header {
  background-color: gold;
}
.centered {
  height: 50px;
  line-height: 50px;
  background-color: deepskyblue;
}
.footer {
  background-color: tomato;
}
<div class="container">
  <div class="wrapper">
    <div class="header">
      <h1>Header</h1>
      <h2>Subheader</h2>
      <p>Text</p>
    </div>
    <div class="centered" contentEditable="true">
      Centered Text - I'm editable, so... EDIT ME !!!!
    </div>
    <div class="footer">
      Some tiny footer
    </div>
  </div>
</div>

还有 FlexyBoxes 工具值得一试。