WrapAware uses a resize observer instead of media queries, and avoids the need for minimum or maximum widths or complex calculations. Do we need CSS flex-wrap detection?
import WrapAware from "wrap-aware";
// WrapAware returns a function that can be called to remove the resize observer
// Accepts a flexbox element, array of flexbox elements, or a query selector
const cleanup = WrapAware('.flex-wrap');
// Easily target with Tailwind classes, eg. ( data-[has-wrapped] & data-[is-wrapped] )
// data-has-wrapped is applied to a flexbox when children are wrapping
<div
data-has-wrapped
class="flex flex-wrap data-has-wrapped:from-pink-500/50"
>
// data-is-wrapped is applied to the wrapped items
<div data-is-wrapped class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">01</div>
<div data-is-wrapped class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">02</div>
<div data-is-wrapped class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">03</div>
...
</div>
A common use-case is to force a flex column layout when the first child has wrapped:
// Force flex-column layout when one item wraps
// Uses :has selector, eg.
<div
data-has-wrapped
class="flex flex-wrap has-data-is-wrapped:flex-col"
>
<div>01</div>
<div>02</div>
<div>03</div>
<div data-is-wrapped>04</div>
</div>
Also works when wrapping flex items in the reverse direction:
<div
data-has-wrapped
class="flex flex-wrap-reverse data-has-wrapped:from-pink-500/50"
>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">01</div>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">02</div>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">03</div>
<div data-is-wrapped class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">04</div>
</div>
Padding applied to the parent flexbox when children wrap doesn't affect detection:
<div
data-has-wrapped
class="flex flex-wrap has-data-is-wrapped:from-pink-500/50 has-data-is-wrapped:px-16"
>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">01</div>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">02</div>
<div class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">03</div>
<div data-is-wrapped class="data-is-wrapped:bg-pink-500 data-is-wrapped:border-pink-400 data-is-wrapped:shadow-pink-900/80">04</div>
</div>
Created and Maintained by Chase Giunta