Flexbox 中内容居中的等高列

Equal height columns with centered content in flexbox

我想要两列等高,它们的内容应该居中对齐,所以在每列的正中央 div。

问题: 'equal height' 和 'middle aligned' 似乎相互排斥,一个不能与另一个一起使用。

问题:如何创建一个包含两列的行,两列的宽度不同,高度相同,并且它们的内容位于每列的中间?

<!-- 'middle aligned' and 'equal height' don't like each other ? -->
<div class="ui equal height center aligned grid">
    <div class="row">
        <div class="twelve wide purple column">
        <p>Text Text Text</p>
        <p>Text Text Text</p>
        <p>Text Text Text</p>
        <p>Text Text Text</p>
        </div>
        <div class="four wide red column  middle aligned">
            <div class="row">Forward</div>

        </div>
    </div>
</div>

http://jsfiddle.net/kjjd66zk/1/

您需要为元素指定高度

.height {
  height: 300px;
}
.row {
  height: 100%;
}
.row > div {
  height: 100%;
}

Updated fiddle 1

如果您希望它们垂直居中,请将上述 .row > div 规则更新为此

.row > div {
  height: 100%;
  display: flex !important;
  flex-direction: column;
  justify-content: center;
}

Updated fiddle 2

此布局的关键是对主弹性容器应用相同的高度。

然后将弹性项目做成嵌套的弹性容器,可以让弹性项目的内容居中。

因此,顶层创建了相同的高度。第二层做居中。

(详见底部注释。)

这是一个基于您的代码结构的示例:

body {
    height: 300px;             /* for demo purposes */
    color: white;
}

flex-container {
    display: flex;             /* primary flex container */
    flex-direction: row;       /* horizontal alignment of flex items
                                      (default value; can be omitted) */
    align-items: stretch;      /* will apply equal heights to flex items
                                      (default value; can be omitted) */
    height: 100%;
}

flex-item {
    display: flex;             /* nested flex container */
    flex-direction: column;    /* vertical alignment of flex items */
    justify-content: center;   /* center flex items vertically */
    align-items: center;       /* center flex items horizontally */
}

flex-item:first-child {
    flex: 3;                   /* consume 3x more free space than sibling */
    background-color: #a333c8;
}

flex-item:last-child {
    flex: 1;
    background-color: #db2828;
}
<flex-container>
    <flex-item><!-- also flex container -->
        <p>Text Text Text</p>
        <p>Text Text Text</p>
        <p>Text Text Text</p>
        <p>Text Text Text</p>
    </flex-item>
    <flex-item><!-- also flex container -->
        <div>Forward</div>
    </flex-item>
</flex-container>

jsFiddle demo


人们有时会认为弹性项目及其内容是一个元素。这是不正确的。

弹性容器的HTML结构分为三层:

  • 容器
  • 项目
  • 内容

因此,项目内的内容并不代表该项目;它代表一个单独的元素。

如果项目中的内容是文本,它将成为匿名元素。

来自 flexbox 规范:

4. Flex Items

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

这就是为什么在上面的解决方案中,弹性项目变成了弹性容器。它允许在弹性项目(内容)的子项上使用弹性属性。