Centering columns in CSS Grid

Hello, Here is what am trying to achieve in CSS Grid. Columns are 50% of the container minus gap. Odd columns center to the container. On mobile/small screen, columns become full width (only mentioning as I think this can be achieved without a media query?) I have mocked this up (badly I might add) in flexbox at this url. https://codepen.io/grantsmith/pen/BaPEMqB I have no errors as such, just can not figure out how to achieve the above in Grid.
6 Replies
Wolle
Wolle2y ago
Grid-children cannot escape afaik, so they are bound to the grid. You could 1) let them span and give them margin-inline: auto, but you would have to get it to have the correct width... 2) use transform: translate (you will have to include the gap in your calculation) There are probaly other solutions, these are the two that came to my mind and I think are reasonable.
MarkBoots
MarkBoots2y ago
with grid, you could do something like this Make a 4colum grid, give all cards a column span of 2 and when the last child is odd, let it start at the second column
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 350px;
gap: 1.5rem;
}
.card {
grid-column-end: span 2;
background-color: blue;
}
.card:last-child:nth-child(odd){
grid-column-start: 2
}
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 350px;
gap: 1.5rem;
}
.card {
grid-column-end: span 2;
background-color: blue;
}
.card:last-child:nth-child(odd){
grid-column-start: 2
}
demo: https://codepen.io/MarkBoots/pen/zYLXXjx
Grant
Grant2y ago
That's a neat solution, thanks very much, I was just about to revert back to grid! Could I use a minmax solution to avoid a media query?
MarkBoots
MarkBoots2y ago
uhm, have to think about that, because im setting the last odd one to grid column 2, it will break with this I thought you would allways wanted 2 columns because you said 50%
Grant
Grant2y ago
Sorry, just thinking out loud, easier enough to write a media query. Thanks again for the help
MarkBoots
MarkBoots2y ago
yea, a media query would be the most logical and easiest way
Want results from more Discord servers?
Add your server