how to center grid item horizontally
I'm using grid to create 3 columns. I want to center grid items of last row horrizontally if there is no enough items for the row. How can I solve this problem? I tried
justify-content:center
but it not work10 Replies
The whole point of grid is that the cells are aligned.
To be able to do this using grid you will need to double the number of grid columns, place each "card" in 2 columns and then, somehow, detect if there are less than 3 items on the last row, update their column start position accordingly to offset them. This of course will change depending on if there are 1 or 2 items.
The key thing here here is just how to detect if there are less than 3 columns. Maybe with a combination of
:not()
, :has()
, :nth-child()
and :empty
🤔 (pops off to Codepen)
Alternatively you could use flex...Sorry, Im not good at css. If I use flex how can I divide the column?
OK, that was actually simpler than I expected. You have got to love the power of
:has()
(though this case might also have been possible using sibling selectors)
Note, this solution as is will only work if you have a known number of rows (ie 2 in this case):
Here is a working example:
https://codepen.io/cbolson/pen/MWMzLxaOk I will look into it
I have added some comments to help explain what is happening.
I have also added a flex version.
The advantage of using flex is that it will work for any number of rows whereas the grid method requires knowing how many rows we have (at least in my current version).
Bear in mind that flex and grid have other differences which might influence which is better for your use case.
wouldnt subgrid help here?
It seems like using
flex
in this case is more easierSome great articles about achieving this via grid:
- https://css-irl.info/controlling-leftover-grid-items/
- https://ryanmulligan.dev/blog/grid-stacks/
But yes, I agree flex is probably the cleaner solution, especially for a generalised use case where you don't know the count
CSS { In Real Life } | Controlling Leftover Grid Items with Pseudo-selectors
CSS { In Real Life } | Controlling Leftover Grid Items with Pseudo-...
Center Items in First Row with CSS Grid
Stacking grid items so that an odd number of items appears horizontally centered in the first row instead of the last.
@Alex @Chris Thanks guys
Thanks for that.
Using the last-child selector makes more sense 🤦♂️
Also defining the column end makes things easier.
I have updated my pen to use this method.
With this method there is no need to know the number of rows, even when using grid 👍