使用 flexbox 以 CSS 为中心的文本

text centering on CSS with flexbox

我正在学习 flex box,但无法让我的文本居中对齐。

我知道我可以使用 padding 垂直居中对齐,但我希望它更像是自动居中,而不是每次都编辑每个项目。

虽然 this link 确实有帮助,但这不是我想要的。

我需要用最少的代码让我的 .item 水平和垂直居中。

CodePen

.parent {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-around;
  flex-wrap: wrap;
}
.item {
  color: white;
  margin: 0px;
  width: auto;
  height: 200px;
  background-color: blue
}
<div class="example">
  <h2> Display: flex </h2>
  <div class="example-content">
    <div class="parent">
      <div class="item">If you wanna</div>
      <div class="item">Then you gotta</div>
      <div class="item">Go findz it</div>
    </div>
  </div>
</div>

您需要添加 align-items:center 和一个新的 display:flex 到 child

body {
  margin: 0
}
.parent {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-around;
  flex-wrap: wrap;
  border: black solid;
  color: white
}
.item {
  display: flex;
  align-items: center;
  height: 200px;
  background: lightgreen;
}
<div class="example">
  <h2> Display: flex </h2>
  <div class="example-content">
    <div class="parent">
      <div class="item">If you wanna</div>
      <div class="item">Then you gotta</div>
      <div class="item">Go findz it</div>
    </div>
  </div>
</div>

要在 .parent 中居中 .item 个子项,请使用以下代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            .parent {
                display: flex;
                align-items: center;
                justify-content: center;
                height: 200px;
            }
            .item {
                align-content: center;
            }
        </style>
    </head>
    <body>
        <div class="example">
            <h2> Display: flex </h2>
            <div class="example-content">
                <div class="parent">
                    <div class="item">If you wanna</div>
                    <div class="item">Then you gotta</div>
                    <div class="item">Go findz it</div>
                </div>
            </div>
        </div>
    </body>
</html>