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

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

问题描述

我试图在使用 justify-content:stretch; 时将 flexbox 项目的内容居中 看来使用 display:table-cell;vertical-align 的老技巧:middle; 在这种情况下不起作用.有什么作用?

.flex-container {显示:弹性;对齐项目:居中;对齐内容:拉伸;}.flex-item {对齐自我:伸展;}<div class="flex-container"><div class="flex-item">我要垂直居中!但我不是.</div>

回答之前:我问的问题似乎很混乱.我试图将弹性项目的 CONTENTS 居中.使用 justify-content:stretch,item 的高度会拉伸到容器的整个高度,但是 item 的 contents 会浮动到顶部(至少在铬).

一张图片胜过一千个字."(A) 是我已经得到的.(B) 是我想要的.

解决方案

可以通过将每个 flex item display 作为一个 flex 容器然后对齐内容来实现垂直通过align-items属性,如下:

.flex-container {显示:弹性;对齐项目:居中;高度:200px;/* 用于演示 */}.flex-item {对齐自我:伸展;显示:弹性;对齐项目:居中;背景颜色:金色;/* 用于演示 */}

<div class="flex-item">我想垂直居中!<s>但我不是.</s>

作为旁注,如果您省略 .flex-containeralign-items:center; 声明,您可以安全地删除 align-self:stretch; 也来自弹性项目.

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>

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 picture is worth a thousand words." (A) is what I've already got. (B) is what I want.

解决方案

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>

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天全站免登陆