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
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
Well i want to change justify-content from space-evenly to space-between when this element goes down
When it goes down like this i want it to space-between
I need it to be dynamic because there can be more then 2 items in the div
@MarkBoots any ideas? 🙂
no, can't think of any without js.
I was trying some container size queries, but they need defined sizes to work
yea, thank you for taking some time out of your day to try it 😊
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”?
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)
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.
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.