将CSS flex元素的高度设置为相同的数量? [英] Set height of CSS flex elements to the same amount?

查看:662
本文介绍了将CSS flex元素的高度设置为相同的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我彼此相邻有2个div,它们使用flex和justify-content / align-items垂直和水平居中。

I have 2 divs next to each other that I center vertically and horizontally using flex and justify-content/align-items.


HTML示例:

Example HTML:

<div class="inner">
    <div class="section green">
        <img src="http://i.imgur.com/hEOMgVf.png">
    </div>
    <div class="section red">
         <img src="http://i.imgur.com/nEybO1g.png">
    </div>
</div>

CSS:

.inner {
    float: left;
    width: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #343434;
    text-align: center;
}
.section {
    float: left;
    flex: 1;
}

.green { background-color: #7dc242; }
.red { background-color: #ed1c24; }

我的问题是我需要将两个 section div的高度设置为与以及将它们垂直和水平居中。您可以在下面的JSFiddle中看到,绿色背景与红色背景的高度不同。如何使两个div都达到容器div的整个高度?

My issue is that I need to set the height of both 'section' divs to the same as well as centering them vertically and horizontally. You can see in the JSFiddle below that the green background isn't the same height as the red. How can I make both divs the full height of the container div?

这是我所拥有的简化的JSFiddle:
http://jsfiddle.net/beK28/1/

Here's a simplified JSFiddle of what I have: http://jsfiddle.net/beK28/1/

推荐答案

要获得所需的效果,请勿尝试在容器元素中进行任何对齐,而应将 .section 设置为是 display:flex 。然后,您可以在子元素中正确地对齐和居中放置图像。

To achieve the effect you want, you shouldn't try to do any of the alignment in the container element and instead should set .section to also be display:flex. Then you can justify and center the images correctly within the children elements.

.section {
    align-items: center;
    display: flex;
    flex: 1;
    justify-content:center;
    text-align: center;
}

http://jsfiddle.net/beK28/8/

您也不需要使用float,那就是整个使用灵活容器的要点。

You also don't need to use float, that's the whole point of using flexible containers.

这篇关于将CSS flex元素的高度设置为相同的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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