How to vertically center the contents of a flexbox item

*爱你&永不变心* 提交于 2019-12-20 09:39:21

问题


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.


回答1:


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.




回答2:


I'm not sure if I am interpreting your request correctly, but I think you are trying to use "justify-content:stretch;" when you should be using flex-grow.

Im my sample I used flex:1 auto; which is just shorthand to set a couple of flex properties.

HTML:

<div class="flex-container">
    <div class="flex-item">I'm top dog!
    </div>
    <div class="flex-item flex-center">
        I want to be vertically centered! And I am!
    </div>
</div>

CSS:

*{
    box-sizing:border-box;
    padding:5px;
}
.flex-container {
    border: 1px solid;
    display:flex;
    align-items:center;
    height: 100px;
}
.flex-item {
    flex: 1 auto;
    border: 1px solid green;
    height:100%;
    display:flex;
    justify-content:center;
}
.flex-center {
    align-items: center;
}

http://jsfiddle.net/p28tjskq/

Flex property:
https://developer.mozilla.org/en-US/docs/Web/CSS/flex



来源:https://stackoverflow.com/questions/28254332/how-to-vertically-center-the-contents-of-a-flexbox-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!