html - 我可以使用 100% 高度而不是 100vh 的 flex 在 body 中垂直居中吗?

标签 html css flexbox

<分区>

我想让 div 居中在正文中。如果我将 100% 更改为 100vh,它会起作用。我想避免使用 100vh,因为我希望这些规则可以在容器中使用。为什么 100% 扩展了背景的高度而不是为了使 div 垂直居中?

head + * {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #cb9800;
  height: 100%;
}

.content {
  font-family: Comic Sans MS;
  font-size: 75%;
}
<div class="content">This is vertically centered if I change 100% to 100vh</div>

最佳答案

html, head + * {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #cb9800;
  height: 100%;
}

.content {
  font-family: Comic Sans MS;
  font-size: 75%;
}
<div class="content">This is vertically centered if I change 100% to 100vh</div>

    height: 100%;

您还需要将高度 100% 添加到 HTML 标签。

关于html - 我可以使用 100% 高度而不是 100vh 的 flex 在 body 中垂直居中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50460677/

相关文章:

javascript - 如何使用 Javascript 中声明的图像编写用于翻转图像的 CSS?

html - 无法滚动到容器溢出的 flex 元素顶部

javascript - 加载 html 或 JavaScript 文件作为 iframe 源

javascript - wait.until(ExpectedConditions.elementToBeClickable) 不起作用

html - 如何在悬停时为元素设置动画

css - Bootstrap flex 方向 - 行和列 -

css - 带/不带柔性的盒子定位

HTML 响应式网格,中间行下方有线

html - 我可以使用元标记来确保我的网站按比例缩小以适应 iPad 视口(viewport)吗?

CSS 过滤器 : Invert does not work in mozilla