Search code examples
htmlcsscenterflexbox

Set height of CSS flex elements to the same amount?


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

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; }

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?

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


Solution

  • 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/

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