使用100%高度的flexbox垂直居中。

8

是否可以使用flexbox在背景颜色方面实现水平垂直居中?

.wrapper {
  display: flex;
  width: 100vw;
  height: 100vh;
  text-align: center;
}

.item {
  flex: 1;
  background-color: green;
  align-self: center;
  justify-content: center;
}
<div class='wrapper'>
  <div class='item'>
    sdafsdfs
  </div>
</div>

如果我添加一个height: 100%,文本会移回到顶部。

不加 height: 100% 吗?你的代码片段对我有效。 - Gezzasa
当您添加 height: 100% 时,它会失败的原因是它没有设置高度的父元素,因此具有默认高度。 - Jesse
{btsdaf} - A. L
如果您想要将任何内容垂直和水平居中,那么您应该在要居中的元素的父级元素中添加 display: flex; align-items: center; justify-content: center - Jesse
1个回答

14
请为您的项目添加display: flex样式。只有这样它才能根据您的要求对内部项目进行对齐。请查看更新后的代码。

.wrapper {
  display: flex;
  width: 100vw;
  height: 100vh;
  text-align: center;

}

.item {
  display: flex;
  background-color: green;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;

}
<div class='wrapper'>
  <div class='item'>
    sdafsdfs
  </div>
</div>

希望这能帮到您


10
这个答案不能被接受,它假设页面高度为100%,而不是父元素高度为100%。 - Altin
如果您觉得这不应该是被接受的答案,您必须提供自己的答案。 - Rajan Benipuri
1
我后来找到了答案: display:flex; flex-direction: column; justify-content: center; - Altin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接