如何垂直居中flexbox项目的内容 [英] How to vertically center the contents of a flexbox item

查看:194
本文介绍了如何垂直居中flexbox项目的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用 justify-content:stretch; 时将flexbox项目的CONTENTS居中;似乎使用 display:table-cell; vertical-align:middle; 在这种情况下不工作。什么是?

I'm trying to center the CONTENTS of a flexbox item while using justify-content:stretch; It appears that the old trick of using display:table-cell;vertical-align:middle; doesn't work in this situation. What does?

.flex-container {
    display:flex;
    align-items:center;
    justify-content:stretch;
}
.flex-item {
    align-self:stretch;
}

<div class="flex-container">
    <div class="flex-item">I want to be vertically centered! But I'm not.</div>
</div>

在回答之前:似乎有很多混淆问。我试图集中弹性项目的 CONTENTS 。使用 justify-content:stretch ,商品的高度将拉伸到容器的整个高度,但内容顶部(至少在Chrome中)。

BEFORE YOU ANSWER: There seems to be a lot confusion about what I'm asking. I'm trying to center the CONTENTS of the flex-item. With justify-content:stretch, the height of the item will stretch to the full height of the container, but the contents of the item floats to the top (at least in Chrome).

图片值得一千字。 (A)是我已经有了。 (B)是我想要的。

"A picture is worth a thousand words." (A) is what I've already got. (B) is what I want.

推荐答案

它可以通过显示将每个flex项目作为 flex 容器然后通过 align-items 属性垂直对齐内容,如下所示:

It can be achieved by displaying each flex item as a flex container and then aligning the contents vertically by align-items property, as follows:

.flex-container {
  display:flex;
  align-items:center;
  height: 200px; /* for demo */
}

.flex-item {
  align-self:stretch;
  display:flex;
  align-items:center;
  background-color: gold; /* for demo */
}

<div class="flex-container">
    <div class="flex-item">
      I want to be vertically centered!
      <s>But I'm not.</s>
  </div>
</div>

- 注意,如果省略 .flex-container align-items:center; 声明, align-self:stretch; 也从flex项目。

As a side-note, if you omit the align-items:center; declaration of the .flex-container you can safely remove align-self:stretch; from flex items as well.

这篇关于如何垂直居中flexbox项目的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆