【问题标题】:text centering on CSS with flexbox [duplicate]使用 flexbox 以 CSS 为中心的文本 [重复]
【发布时间】:2016-07-05 01:06:58
【问题描述】:

我正在学习 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>

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

    要在 .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>
    

    【讨论】:

      【解决方案2】:

      您需要为孩子添加align-items:center 和一个新的display:flex

      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>

      【讨论】:

        猜你喜欢
        • 2018-07-30
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 2016-11-26
        • 2021-07-22
        • 2020-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多