I have an image
in a flex container (let's call it child
).
The container itself has flex: 1
because it also belongs to a flex parent
with flex-direction: column
and child
behaves as expected (takes 100% height of parent) before introducing the image situation.
On adding an image to child
, the image extends child
to accommodate its height, effectively child
pushing parent
.
Using object-fit: cover
on the image could not help in this situation!
Looks like this is normal behaviour in Chrome, Firefox, and Safari.
Here's the weird part tho: adding a height
property to child
fixes the issue on Chrome and Safari but not Firefox. This height's value doesn't matter much as long as it's not greater than the computed height of child
- child
is contained to 100% height
of parent
together with the image - even if the height value of child
is set to 1px
. Surprisingly height: 100%
on child
doesn't produce the same behaviour.
Any ideas around this will be much appreciated. My goal is to make the image
always take up 100% of child
- regardless of the width of the viewport.
Here's some code for illustration
#parent {
height: 100vh;
display: flex;
flex-direction: column;
}
#child {
flex: 1;
height: 1px;
/* the weird hack for chrome and safari - ff ignores it */
}
#child img {
width: 100%;
height: 100%;
object-fit: cover;
}
<div id="parent">
<div id="child">
<img src="https://i.picsum.photos/id/1005/400/1000.jpg" />
</div>
</div>
I also added some images for more context. These are crops of the entire page. The first image is from a smaller viewport (width shared with devtools) and the second from the entire page (devtools hidden). The second image shows that the image
has extended child
to eventually push the container with a green background beyond the fold - causing a scrollbar to appear.
child
is the image wrapper, and parent
is the component with a white background and some padding. You realize parent
has a sibling (green background) and their parent (container with a green border and border radius) has a display: grid
and grid-template-rows: 1fr auto;
.
It should also be noted that the most top-level element has a height of 100vh
and all its children are rendered within that. Essentially there should not be a scrollbar.
I hope you get the idea.