Is there a way to detect when an element wraps using only CSS (flexbox or grid)?

This article https://ishadeed.com/article/flex-wrap-detect/ probably answers my question, but I was wondering if maybe some new feature came up in CSS for this or maybe the article missed something?
Do we need CSS flex-wrap detection?
A look at why we need flex wrapping detection in CSS.
9 Replies
MarkBoots
MarkBoots7mo ago
i don't think it is really possible. but before we dive into it more.... What do you want to do with it if we can detect it? Maybe there are other options
relja
reljaOP7mo ago
Well i want to change justify-content from space-evenly to space-between when this element goes down
No description
relja
reljaOP7mo ago
When it goes down like this i want it to space-between
No description
relja
reljaOP7mo ago
I need it to be dynamic because there can be more then 2 items in the div @MarkBoots any ideas? 🙂
MarkBoots
MarkBoots7mo ago
no, can't think of any without js. I was trying some container size queries, but they need defined sizes to work
relja
reljaOP7mo ago
yea, thank you for taking some time out of your day to try it 😊
Hashi
Hashi7mo ago
Could it maybe work with container query that is based on the height, if it’s bigger than x then most likely it’s more than one “line”?
MarkBoots
MarkBoots7mo ago
for that the container needs to have an initial intrinsic height. it could work, but it's a bit magic numbery (and not sure it will cause issues in certain scenarios)
ArturM
ArturM2w ago
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.

Did you find this page helpful?