ArturM
ArturM
KPCKevin Powell - Community
Created by relja on 7/15/2024 in #front-end
Is there a way to detect when an element wraps using only CSS (flexbox or grid)?
Yeah, no way of doing it in pure CSS 🥺 . I wouldn't root for it becoming a feature in CSS anytime soon. There are issues like infinite loops, a need for 2 pass rendering.. it's not easy to do let just say. But it IS possible - using JS obviously. Check out this custom element I have build: <flex-wrap-detector> (docs, examples) This is as close to pure CSS as you can get. You'd need to import the script <script src="https://unpkg.com/fluid-flexbox@latest/dist/web/flex-wrap-detector.umd.js"></script> And wrap your flex container with the detector, in the HTML specifying what class to add to it when the flex items start wrapping.
<flex-wrap-detector wrapped-class="justify-between">
<div class="flex shrink-0 grow">
/* .. flex items ... */
</div>
</flex-wrap-detector>
<flex-wrap-detector wrapped-class="justify-between">
<div class="flex shrink-0 grow">
/* .. flex items ... */
</div>
</flex-wrap-detector>
That's it. It uses JS but it hides it pretty well 😉 and the script is tiny <6kb unminified. You can do a lot more than just applying alternative CSS, including providing completely alternative content, nesting etc.. The simple usage should work for most cases tough.
11 replies