Place-items:center not having the desired effect for grid elements

Trying to get better at css and got stuck on some grid funk. I have a grid that has 8 columns. The grid can contain any number of grid items, all which span 2 columns. If there are 4n grid items, they fill out the grid nicely. But if there are less than that, say 2, the grid items arrange themselves starting at the left most side. Looking for a clean solution as place-items:center wasn't the solution.
.products__list-wrapper {
display: grid;
grid-template-columns: repeat(8, 1fr);
place-items:center;
}
.item__wrapper{
grid-column: span 2;
}
.products__list-wrapper {
display: grid;
grid-template-columns: repeat(8, 1fr);
place-items:center;
}
.item__wrapper{
grid-column: span 2;
}
https://codepen.io/fluffybacon-steam/pen/WNLWRPe
No description
4 Replies
MarkBoots
MarkBoots8mo ago
There is not really a native way to do it. a grid is 2 dimensional an will start filling the items from top left to bottom right. But, with creative combining nth-child selectors, you can adjust the position of a specific child. For example: if the 4n + 1 is also the last child, start at column 4, if it is the 2n last, start at 3, etc...
.grid {
display: grid;
grid-template-columns: repeat(8, 1fr);
}
.grid-item { grid-column-end: span 2; }
.grid-item:nth-child(4n + 1):nth-last-child(1) { grid-column-start: 4; }
.grid-item:nth-child(4n + 1):nth-last-child(2) { grid-column-start: 3; }
.grid-item:nth-child(4n + 1):nth-last-child(3) { grid-column-start: 2; }
.grid {
display: grid;
grid-template-columns: repeat(8, 1fr);
}
.grid-item { grid-column-end: span 2; }
.grid-item:nth-child(4n + 1):nth-last-child(1) { grid-column-start: 4; }
.grid-item:nth-child(4n + 1):nth-last-child(2) { grid-column-start: 3; }
.grid-item:nth-child(4n + 1):nth-last-child(3) { grid-column-start: 2; }
note: this will only work with a fixed amount of columns. To make it responsive, you'll have to adjust it in media queries
No description
fluffy bacon
fluffy bacon8mo ago
>There is not really a native way to do it I was afraid of that, but good to know. Thanks for the response! I am not sure how to mark this as solved but SOLVED!
Rägnar O'ock
Rägnar O'ock8mo ago
What you need is a flexbox
fluffy bacon
fluffy bacon8mo ago
You're totally right. I just switched to flex-wrap justify-content:center and its looks great now. I still struggle when to use grid vs flex