I have a div where elements are added and removed dynamically. Is there a way to make them fit into the pattern shown in the image? There will never be more than 5 elements in the div at one time.
If you have a known maximum number of child elements you can specify positioning in a CSS-Grid based on the number of each specific child and how many it is from the end.
For instance 2nd of 3 is .child:is(:nth-child(2)):is(:nth-last-child(2))
..and so on. This does lead to a number of selectors for each child, for example in a 5 child box – item 2 needs 4 rules, items 3 needs 3, 4 needs 2 and 5 only one.
Here I have stuck to a 4 child example but the pattern remains the same.
2
Answers
If you have a known maximum number of child elements you can specify positioning in a CSS-Grid based on the number of each specific child and how many it is from the end.
For instance 2nd of 3 is
.child:is(:nth-child(2)):is(:nth-last-child(2))
..and so on. This does lead to a number of selectors for each child, for example in a 5 child box – item 2 needs 4 rules, items 3 needs 3, 4 needs 2 and 5 only one.
Here I have stuck to a 4 child example but the pattern remains the same.
Actually you don’t need too much code
Related article to get more detail about the technique I am using above: https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/