首页 > 解决方案 > 如何垂直对齐父 div 的 ap 子项,以便轻松地对子项进行文本对齐?

问题描述

我的目标是垂直对齐父 div 的子 p。目前,我使用 Flexbox。但它阻止我修改文本对齐。

我的预期结果:文本是垂直对齐的,并且可以是文本对齐的。

我的实际结果:文本是垂直对齐的,但它不能是文本对齐的。

body {
 background-color: silver; 
}
div {
  background-color: white;
}
header, nav, section, article, aside, footer {
  background-color: white;
  padding: 10px;
  border: solid;
}
.text-center {
  text-align: center;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
  <div style="display: flex;">
    <div style="flex: 1;">
      <section>
        <p class="text-center">Section</p>
      </section>
      <article>
        <p class="text-center">Article</p>
      </article>
    </div>
    <aside class="center" style="flex: 1;">
      <p style="text-align: right;">Aside</p>
    </aside>
  </div>

在旁边

标签: css

解决方案


这是你要找的吗?(抱歉不得不稍微改变一下课程)。我所做的是添加了一个显示:网格;和对齐项目:中心;在 p 标签的所有父母身上。

HTML:

<div class="flex">
        <div class="flex-item">
            <section>
                <p class="text-center">Section</p>
            </section>
            <article>
                <p class="text-center">Article</p>
            </article>
        </div>
        <aside class="center flex-item">
            <p>Aside</p>
        </aside>
</div>

CSS

  body {
   background-color: silver; 
  }
  div {
   background-color: white;
  }
  header, nav, section, article, aside, footer {
   background-color: white;
   padding: 10px;
   border: solid;
  }
 .flex {
   display: flex;
 }
 .flex-item {
   flex: 1;
 }
 .flex-item section,
 .flex-item article,
 .center {
  display: grid;
  align-items: center;
  text-align: center;
 }
 .flex-item section,
 .flex-item article {
   height: 200px; /* this is just to see the vertical layout */
 }

您现在应该能够自由对齐左、中和右,但还有更多方法可以做到这一点。如果您担心使用网格,它有很好的支持,并且在大多数主流浏览器上都能正常工作:)


推荐阅读