Recently I saw this tweet float by:
CSS experts, I need your help! 👇
I need a container that vertically centers its children and that can be scrollable if necessary.
It should be a single container. Not 2.
<div class="container">
<item>Vertically centered</item>
<item>Vertically centered</item>
</div>— Álvaro Trigo 🐦🔥 (@IMAC2) September 24, 2021
Now that sounds like a job for CSS Grid to me!
See the Pen CSS Full-Height Slideshow with Centered Slides by Bramus (@bramus) on CodePen.
The code is documented, yet the key part here is to:
- Use
grid-auto-rows: 100vh
(or soon100dvh
) on the container to place the children inside rows of100vh
each. - Use
place-items: center;
on the container to center the items themselves inside their assigned row.
Because we’re using grid-auto-rows
, the code will work with any number of direct children in the container.
~
🔥 Like what you see? Want to stay in the loop? Here's how: