尝试对齐列表容器内的文本时出现问题

Issues attempting to align text inside of list containers

我有一排四个 li 容器,每个容器内都有 H3 文本。我希望文本在垂直和水平方向上都居中,但只能垂直放置。尝试了无数次 vertical-align: middle;但没有运气。这是我正在使用的。

HTML:

<ul class="products oceanwp-row clr grid shop-variety">
    <li style="background-image: url( http://flowerlinkla.com/staging/wp-content/uploads/2018/12/bkg-garden-rose.jpg ) !important;" class="shop-variety product col span_1_of_4"><div class="shop-content"><h3>Garden Rose</h3></div></li>
</ul>

CSS:

.shop-variety.product.col.span_1_of_4 {
    height: 285px;
    width: 24%;
    margin: 24px .5%;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}

应该提到我也试过 display: flex。运气不好。

http://flowerlinkla.com/staging/shop/

既然你说你尝试 display: flex,它需要一些其他属性,例如 justify-content and align-items

.shop-variety.product.col.span_1_of_4 {
  /* Remove */
  display: table-cell;
  vertical-align: middle;

  /* Add */
  display: flex;
  justify-content: center;
  align-items: center;
}

输出:

@manoj-kumar 的回答很完美。 澄清一下,justify-content 在主轴上对齐子元素。 例如,如果您将 flex 水平放置(flex-direction: row - 这是默认值),justify-content: center 将使子元素水平居中。

另一方面,align-items 会将其对齐到辅助轴上。如果您将 flex 垂直放置 (flex-direction: column),align-items: center 将使子元素水平居中,justify-content: center 将使子元素垂直居中。

这里有一个CodePen,使它在视觉上更清晰。 ;)

在这里您可以阅读所有关于 Flexbox 属性的信息。 [https://css-tricks.com/snippets/css/a-guide-to-flexbox/]

希望对您有所帮助。