使用 Flexbox 在全高页面上垂直对齐

use*_*783 2 css flexbox

我正在尝试创建简单的页面,其标题和导航栏由内容区域分隔。我无法强制 div#cover垂直居中对齐。我希望我的设计具有响应能力,因此我不想在父 div 上指定宽度content。我知道我可以用来flex: 1填充该区域的其余部分,但我尝试过,但它对我不起作用。

请看这里:Codepen

.site-content {
  display: flex;
  flex-direction: column;
}
.navbar {
  display: flex;
  justify-content: space-between;
}
nav ul {
  display: flex;
  list-style-type: none;
}
li {
  margin: 0 10px;
}
.content {
  display: flex;
  flex: 1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="site-content">
  <div class="navbar">
    <div class="title">TitLe</div>
    <nav>
      <ul>
        <li>link1</li>
        <li>link2</li>
        <li>link3</li>
      </ul>
    </nav>
  </div>
  <div class="content">
    <div id="cover">
      Lorem ipsum
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Sti*_*ers 5

您需要定义heightfor .site-content

.site-content {
  display: flex;
  flex-direction: column;
  height: 100vh; /*new*/
}
Run Code Online (Sandbox Code Playgroud)

html或者在、body和标签上设置百分比高度.site-content

html, body, .site-content {
  height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

body还可以根据需要重置默认边距。

body {
  margin: 0;
}
Run Code Online (Sandbox Code Playgroud)

要垂直居中#cover,请align-items在容器上使用。

.content {
  display: flex;
  flex: 1;
  align-items: center; /*new*/
}
Run Code Online (Sandbox Code Playgroud)

更新了 Codepen