How to vertically center the whole grid container?

I want the whole thing in the center of the page. I was able to get it horizontally centered by using margin: auto (though I suspect that may not be the proper way of horizontally centering a grid). I have tried align-items: center and place-items: center and they don’t do much of anything. I have also tried margin: 0 auto and that didn’t do anything different from margin: auto. The grid container is .grid-container.

This is just one option, but you could add the following CSS

/* ensure the window fills the available screen height */
body {
  height: 100%;

/* center the children of body */
body {
  display: grid;
  place-items: center;

That didn’t do anything for me.

This is what you’re looking for, right? With the grid centered in the page vertically and horizontally.

Ok, I get it now. It’s working. But can you please explain how this works? Why do I need to turn the body into a grid too, in addition to the actual grid? I also don’t understand how the height: 100% fits in and why it is required on both html and body selectors.

Like I said, this is just one option.

First off, to get vertical centering within the viewport, you need to make sure your root element (the element that will center its children vertically, body in this case) has a height equal to the viewport. In this case, you can do that by setting html and body to height: 100%.

Making body a grid was simply to be able to use place-items: center (you could also use flexbox with align-items and justify-content both set to center).

1 Like

Thank you. I appreciate it.