I want to define a set of css rules to accomplish the following effect: I have a variable amount of child items of fixed size that need to be arrange in columns. If the items reach a certain height, restricted by the parent container (red), they should be arranged in two columns with the items balanced among them. This effect should work for an arbitrary amount of items and columns. At best the parent container should shrink to the size of the new arrangement (blue container). I'm looking for a plain css solution and tried it with flexblox but I think this isn't possible. I also tried it with grid but couldn't get it working yet. Thanks!

-
There is no practical CSS-only solution for it, as CSS is applied to HTML. CSS doesn't know how many child elements an HTML element has. There is no communication between HTML and CSS. In theory, it might be possible to hack into it if you know the exact height of every element beforehand. But it would be easy to break and therefore, a small JS solution would be a more reliable and faster way.tacoshy– tacoshy2025-09-03 14:51:34 +00:00Commented Sep 3 at 14:51
-
Thanks, then I'll use JS to solve it.Ecanyte– Ecanyte2025-09-03 16:54:02 +00:00Commented Sep 3 at 16:54
-
Can you write it yourself, or do you need help with it?tacoshy– tacoshy2025-09-03 16:57:39 +00:00Commented Sep 3 at 16:57
-
It's fine. Got it working with JS.Ecanyte– Ecanyte2025-09-04 20:31:52 +00:00Commented Sep 4 at 20:31
-
I agree with @tacoshy that this is probably not possible in vanilla CSS, at least without having some pretty stringent requirements on fixed, already-known, values for heights. That being said, there is an updated version of CSS Grid that is currently being created that I believe would make this possible within the next few years or so. It's called CSS Grid Level 3: webkit.org/blog/15269/…Sam Sabin– Sam Sabin2025-09-15 02:09:45 +00:00Commented Sep 15 at 2:09
Add a comment
|