Flexbox - 垂直居中文本

新手上路,请多包涵

我有一个方形的 flexbox,完全被一个超链接覆盖。

现在我想将 flexbox 的内容垂直居中。

However, using a div element with the property display: table and a nested div with the property display: table-cell; vertical-align: middle does not work, since I lose the正方形。

如果我使用 div s 而不是 ulli 我失去了能够点击任何地方的属性。

我希望“文本”在红框的水平和垂直中心对齐:

 body {
  margin: 0px;
  width: 100%;
}
main {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.flex-container {
  width: 100%;
}
ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  -webkit-padding-start: 0px;
  -webkit-margin-before: 0px;
  -webkit-margin-after: 0px;
}
li {
  display: flex;
  flex-direction: column;
  width: 50%;
}
.red {
  background-color: red;
}
.white {
  background-color: white;
}
.tile:before {
  content: '';
  float: left;
  padding-top: 100%;
}
.tile {
  text-align: center;
}
 <main>
  <div class="flex-container">
    <ul>
      <li class="red">
        <a href="/">
          <div class="tile">
            Text
          </div>
        </a>
      </li>
    </ul>
  </div>
</main>

原文由 Skrodde 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 258
2 个回答
 main {
  height: 200px;
  width: 200px;
}
a {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: red;
  height: 100%;
}
 <main>
  <a href="/">
    <div class="tile">Text</div>
  </a>
</main>

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

在您的 .tile 声明中,您需要如下的 flexbox 代码:

 justify-content: center;
display: flex;
align-items: center;

你的 LI 声明应该只是 display:block 因为它没有使用 flexbox 属性。

原文由 Zack Kirby 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题