JBE JBE - 6 months ago 10
CSS Question

Flexbox item height independent of its content

I know this sounds like again another question on flexbox which is solved elsewhere but I can't find a solution from google or stackoverflow existing posts.

The problem is simple.

I have 3 children divs inside a parent div, one of them containing a content bigger than its final size. I would like each child to be

1/3
of its parent REGARDLESS of its content.

Here is the fiddle: http://jsfiddle.net/xeqo0msq/

Here is the HTML:

<div class="parent">
<div class="child red">
<div class="content">1</div>
</div>
<div class="child blue">2</div>
<div class="child green">3</div>
</div>


And the associated CSS:

.parent {
display: flex;
flex-direction: column; /*or row*/
height: 100%;
width: 100%;
}

.child {
flex: 1;
}

.content{
width: 800px;
height: 100px;
}

.red {background: red;}
.blue {background: blue;}
.green {background: green;}


For
flex-direction: row;
it works as expected: each child is
1/3
of its parent, although the first content is way bigger. The width acts as if it was independent from the content.

Flex Row screenshot

For
flex-direction: column;
the first child is way bigger than the two others.

Flex Column screenshot

Is it possible to achieve this using flexbox and
flex-direction: column;
?

Joy Joy
Answer

When defining as flex-direction: row, the width of parent is limited by the screen, so it is known. Flex distributes the widths to three children.

But when flex-direction: column, the parent height not known (determined by children). Although you define it as height: 100%, but this 100% is relative to the height of its parent element, which is body. The height of body is not full-screen height.

There are three options for you:

  1. Simply add a height value to .child will make their height controllable: JSFiddle

  2. Limit the .parent height like JSFiddle.

  3. If what you want is each child occupies 1/3 of the screen height, you need to define the height of html, body to be 100% like this demo: JSFiddle

Comments