html - 如何使用 CSS flex 使元素占据页面的 100% 并将元素居中?

标签 html css flexbox

<分区>

我正在尝试 https://stackoverflow.com/a/22218694/1175080 中描述的以下解决方案.

Alternatively, instead of aligning the content via the container, flexbox can also center the a flex item with an auto margin when there is only one flex-item in the flex container (like the example given in the question above).

这是我的解决方案。

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
  main {
      display: flex;
      height: 100%;
      background: lightgreen;
  }

  section {
      margin: auto;
      background: yellow;
  }
</style>
</head>
<body>
  <main>
      <section>Foo</section>
  </main>
</body>
</html>

好像不行。 main 元素不会展开以占据页面的 100% 高度。我究竟做错了什么?如何让它发挥作用?

最佳答案

使用 height:100vh

body {
  min-height: 100vh;
  margin: 0;
}
main {
  display: flex;
  height: 100vh;
  background: lightgreen;
}

section {
  margin: auto;
  background: yellow;
}
<main>
    <section>Foo</section>
</main>

关于html - 如何使用 CSS flex 使元素占据页面的 100% 并将元素居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763847/

上一篇:CSS Flexbox 全高列

下一篇:javascript - 使用 jquery 创建我自己的图片库网格

相关文章:

仅适用于#widget 的 CSS 重置

html - 网页字体的不同样式和粗细是如何渲染的?

javascript - 如何在 css 中的 flex-item 中设置相对边距?

html - 将列表对齐到 flexbox 中容器的左侧

html - 当您单击其中的链接时,Bootstrap panel-collapse 会折叠

javascript - 使用ajax执行php插入功能

html - 为什么我的 <p> 和 <div> 元素不服从显示 : inline?

html - 为什么 Firefox 会截断我的 &lt;input type ="text"/> 中的文本?

css - Loader 在 flex 容器内时不旋转

javascript - Dropzone.js 拖放在 IE10 中不起作用