CSS Grid Layout with an element spanning dynamic number of grid rows
I'm not sure if this is possible but I thought I would ask before I resort to manipulating the dom with javascript since I don't have control of the html. I have a page with a dynamic number of sections and I need to create a 2 column layout for those sections. The first section needs to go into the first column and span all the rows created by the rest of the sections. Since the number of total sections is dynamic, I can't use
grid-row: 1 / -1;
I'd have to do something like grid-row: span 200;
but I also need this first section to be position sticky and this prevents that from working. The only other thing I can think of is using javascript to wrap all the other sections in a div so I only have 1 row within the grid to worry about.
Here is a code pen example of the basic layout I'm going for but I can't use the grid-row: span 3;
that is in the example since I won't know how many rows there could be. https://codepen.io/shborrowman/pen/yyBPNmd
Does anyone know if this is even possible or is the javascript route of placing all but the first section inside a div the only way to go?3 Replies
I don't think that this is possible with CSS alone. As you have already tried, being able to define -1 to extend to the last row would be ideal but that isn't possible without defining the specific number of rows.
I suspect that JS is the only option here.
You could use JS to count the number of rows and dynamically update the grid-template-rows value accordingly. In this case you could use `grid-row: 1 / -1;" on your first child element.
Ya, I figured JS would have to be involved. I can't decide if I would rather count how many rows I need and update the grid with that or just run loop that places all the other sections in a div for me. I usually try to avoid manipulating the dom unless I have to so I was hoping there was some grid magic trick that I hadn't heard about yet hah.
I would count the rows using getComputedStyle() and then update the grid-template-rows via a custom property. No need to manipulate the DOM itself.
a quick demo