I have an unknown amount of elements and next to them they need to have an element always next to them like this:
╔═══════╦═══╗
║ ║ ║
╠═══════╣ ║
║ ║ ║
╠═══════╣ ║
║ ║ ║
╠═══════╣ ║
║ ║ ║
╚═══════╩═══╝
They can’t be two separate containers, my CSS is already quite complex and I’m working with other people as well so it would be quite difficult to change it everywhere.
I tried setting grid-row
on the right element to 1 / -1
, but you can only use negative values if you have explicity set grid-template-rows
, but I don’t know how many columns there are.
Something else I tried was using a CSS counter to set either grid-row-end: counter(count)
or setting grid-template-rows: repeat(counter(count), auto)
, but it doesn’t output a number.
What can I do? Should I just make it be two separate containers? Using JavaScript is not a great solution either.
Edit: a strange solution that isn’t very reliable, but should work in most situations assuming the rest of the layout is known, you can set grid-column: 1 / span 99
. I tried doing 1 / 99
before but this is better and doesn’t create new rows.
2
Answers
Solution 1: With two containers
You can achieve the same output using
flexbox
. You can split your container into two columnsleft
andright
, and the split yourleft
container into four smaller containers. I added an example bellow with fixed dimensions just for referencing. Hope that helps.Solution 2: With One container (Not recommended)
You can achieve that also with one container but I do not recommend it because as you say you the boxes on the left will be dynamic. Here is any example but with fixed elements and fixed heights.
I would suggestion switching to two separate containers since it is a more clear layout for what you want to achieve.
Sounds like you might want to try wrapping the items on the left. Have a look at this article: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_flexible_box_layout/Mastering_wrapping_of_flex_items
I do think it would be better to use two columns like was previously suggested, but if that’s not possible this could be the way.