pau.moreno pau.moreno - 7 months ago 23
HTML Question

Flexbox: fit image vertically with direction: column

I'm trying to fit an image vertically in a flex container which has a specific height.

The

flex-direction
is
column
, and the image is contained in a
flex-item
with
flex-basis: 100%
.

In addition, the image's
max-height
is
100%
.

As you can see in the example, the image does not fit into the red container.



#container {
background-color: red;
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 200px;
width: 320px;
justify-content: space-between;
}

#container > * {
padding: 5px;
}

#img {
flex: 0 1 100%;
/* height: 100%; */
}
img {
max-height: 100%;
max-width: 100%;
}

<div id="container">
<div id="img">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=img&w=340&h=500">
</div>

<div>
Something else
</div>
</div>





Shouldn't the image shrink to fit vertically into the flex container, according to the specification?

The workaround I found is to set the
height
of
#img
to
100%
, but I have the sensation that it's not the way it should be done.

As an additional note, if I set
flex-direction: row
to the container, it fits the image horizontally (which is the behaviour I would expect).

Answer

You wrote:

The workaround I found is to set the height of #img to 100%, but I have the sensation that it's not the way it should be done.

Actually, it is the way it should be done. The predominant implementation of the spec requires that the height property be applied to the parent when using percentage heights on the child. (Although this is slowly evolving. See my second reference below.)

References: