Wrap Detection via Container Size Thresholds
Set a parent div as a named container with container-type: inline-size and container-name: wrap-detector. Target child elements like images with a container query: @container wrap-detector (width > 75vw) { .hero-image { height: 20vh; } }. This detects when the flexbox-wrapped container spans over 75% of the viewport width—common after wrapping due to padding—triggering image height limits. Unlike media queries, viewport units here measure relative to the container's occupied space, enabling intrinsic responsive adjustments without fixed breakpoints.
In a two-column flexbox, unwrapped state keeps the container under 75vw (e.g., ~50% minus padding), so images stay full height. Post-wrap, it exceeds 75vw, shrinking images to prevent overflow. This outperforms picture/srcset elements, which rely solely on viewport size and can't detect local layout shifts.
Nested Containers for Multi-Column Adaptations
For three-column grids, make each column a container: .columns > * { container-type: inline-size; }. Nest the inner wrap-detector query to reference the parent: @container (width > 75cqw) { .hero-image { height: 20vh; } }. Here, cqw (container query width) pulls from the enclosing column's size, detecting effective space even when the top-level detector is narrow.
Fallback to 75vw ensures graceful degradation without nested support. For inverse detection (e.g., two-column vs. stacked), use @container wrap-detector (width = 100cqi) to adjust when fully unwrapped. This layered approach creates 'inception'-like queries, adapting images across layouts: stacked at small widths, constrained in grids, full in side-by-side.
Limitations and When to Use
Requires explicit sizes on flex items to avoid collapse during wrap—pure flex-wrap without dimensions fails. Not for all flex scenarios; best for defined splits like two/three-columns. Container queries complement, don't replace media queries: step outside pixel-based thinking to unlock layout-aware responses. Inspired by Andy Bell's deep dive, which details the trick at the end—read fully for production patterns. Avoid for primary image optimization (use responsive sources), but ideal for secondary height caps in dynamic content.