【问题标题】:Text not centered with justify-content: center文本不以 justify-content 为中心:居中
【发布时间】:2017-02-02 08:48:39
【问题描述】:

我有一个带有 display: flex 的 div。它的内容水平和垂直居中。

当 div 中的内容太长时,内容会换行。但是在这种情况下,对齐被破坏了。请参阅 sn-p。

如果我添加text-align: center,它会正确显示。但是为什么没有text-align: center 就不能居中呢?

.box{
  width: 100px;
  height: 100px;
  background-color: lightgreen;
  margin: 10px;
}

.flex{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.with-align{
  text-align: center;
}
<div class="box flex">
  some long text here
</div>

<div class="box flex with-align">
  some long text here
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    flex 容器的 HTML 结构分为三个层次:

    • 容器
    • 项目
    • 内容

    每个级别代表一个单独的、独立的元素。

    在弹性容器上设置的justify-content 属性控制弹性项目。它无法直接控制项的子项(在本例中为文本)。

    当您在行方向容器上设置 justify-content: center 时,项目会缩小到内容宽度(即缩小以适合)并水平居中。内容在项目内部,随行随行。

    一切都很好地居中,当内容比弹性容器窄时

    另一方面,当内容比弹性容器宽时,弹性项目不能再居中。事实上,该项目根本无法对齐(@9​​87654325@、endcenter),因为没有可用空间——该项目占用了容器的整个宽度。

    在这种情况下,文本可以换行。但justify-content: center 不适用于文本。它从来没有。文本始终受默认text-align: start 的约束(LTR 中的left / RTL 中的right)。

    因此,要将文本直接居中,请将text-align: center 添加到弹性项目(或弹性容器,由于inheritance,这并不重要)。

    article {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .center {
      text-align: center;
    }
    
    /* demo styles only */
    article {
      width: 100px;
      height: 100px;
      margin: 10px;  
      background-color: lightgreen;
    }
    <article>
      <p>some long text here</p>
    </article>
    
    <article>
      <p class="center">some long text here</p>
    </article>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-28
      • 2018-10-21
      • 2021-05-07
      • 2018-01-11
      • 2023-04-06
      • 1970-01-01
      • 2011-09-08
      相关资源
      最近更新 更多