product-preview-card-component-main

Solution retrospective
🖼️ Adaptive Images in Flex Context — Observations & Issues
When working with responsive (adaptive) images inside a flex layout, I've encountered a few non-intuitive behaviors that raised questions.
1.<img>
with width: 100%
doesn't always behave as expected inside flex children
Using the following setup:
.card__preview { flex: 1 1 50%; }
...you'd expect that the <img>
inside would stretch to fill its parent's width. But it often doesn't work unless the image is explicitly wrapped and its dimensions tightly controlled.
In my case, the <img>
didn't respect the container’s calculated width — it either overflowed or collapsed unexpectedly depending on intrinsic dimensions.
I tried to constrain the image height via the parent, but it didn’t work properly. The image would still overflow unless I set the height (or max-height) directly on the <img>
element.
Example fix that worked:
.card__media { max-block-size: 20rem; /* hard limit on image height */ inline-size: 100%; /* stretch to parent width */ object-fit: cover; /* fill while maintaining aspect ratio */ }
Without this direct max-block-size
on the image, the image simply ignored the parent's height restriction and rendered at its natural aspect ratio.
❓Is this expected?
From what I can tell:
- ✅ Setting
width: 100%
on<img>
inside a flex container only works properly if the parent itself has a definite width (from flex-basis or size constraint). - ❌ Limiting height on the image's parent is not enough unless the image itself is also explicitly constrained (via
height
,max-height
, orblock-size
). - ✅ Using
object-fit: cover
helps maintain aspect ratio and cropping when the image is forced into constraints — but it needs bothwidth
andheight
to be explicitly managed.
✅ Best Practice Summary
- Always wrap
<img>
inside a dedicated flex child if working in a flex container. - Set
flex: 1 1 auto
orflex: 1 1 50%
on the wrapper, not the image. - Apply size constraints directly on
<img>
, not just the parent. - Use
object-fit: cover
+inline-size: 100%
+max-block-size
(orheight
) on the<img>
.
This behavior seems to be standard CSS, but not very intuitive when you're aiming for pure "responsive" behavior with flex
and img
.
Please log in to post a comment
Log in with GitHubCommunity feedback
- @DuyTM0508
Oke good
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord