how to center last row item in grid display

how to center last row item in grid display. the center of last row when number of items less than number of grid template columns what is the similar of flex:flex wrap
9 Replies
Kevin Powell
Kevin Powell•17mo ago
you sort of answered your own question there... use flexbox 😄 Grid makes a set grid of rows and columns, and the children live within that grid. With flexbox, each row is independent from the previous one, so you can center across an entire row if there's only one child. If you have a fixed number of grid items, you could do it by selecting the last one and playing with the starting column and maybe even spanning it, but it starts to be more work, and you might not even be able to do what you want. You can technically count children and do some more robust layout changes too using :has() (if you don't mind the lower browser support), but it's a lot easier just to use flexbox
M@HeR
M@HeROP•17mo ago
The problem i use grid because i have parameters to number of columns and row this why i use grid for example i have last row have 3 item and columns parameter is 4 i should center the last 3 elements in last row alse i have the number of all items but i cant to make it dynamically
Wolle
Wolle•17mo ago
You could insert a div with col span in the last row and add the elements in there. (With JS)
M@HeR
M@HeROP•17mo ago
How if you have sample i will be thankful
Kevin Powell
Kevin Powell•17mo ago
If you have 4 columns, there isn't a way to center three items within that space. The only option I can think of would be to use a 12-column grid
Kevin Powell
Kevin Powell•17mo ago
If I understand, right now you have something like this. I have the grid on, so there's no way to have those last three be centered, since they'd split through the existing columns
Kevin Powell
Kevin Powell•17mo ago
Actually, a 12-column grid wouldn't work here... an 8-column grid would though 😄 I have all the children to span 2 here. Then, on the first of the ones in the bottom, I have an offset class to move it over 1 column with grid-column: 2 / span 2
Kevin Powell
Kevin Powell•17mo ago
Here it is with flexbox, which I prefer because it's more dynamic (will work with any amount of content, with no modifier classes needed). The only tricky bit is the flex-basis, since you need to figure it out with the gap, but it's not that bad, and once you've set it up, it just works. https://codepen.io/kevinpowell/pen/jOQeqZJ
Want results from more Discord servers?
Add your server