Search code examples
htmlcssgridcss-grid

Center a grid container vertically and horizontally


Surprisingly, I can't find anything about this online. Maybe I've missed something. How do you horizontally and vertically center your entire main wrapper with CSS Grid, and obviously, maintain responsiveness?

.wrapper {
  display: grid;
  grid-template-columns: minmax(100vw, 1fr);
  grid-template-rows: minmax(100vh, 1fr);
  align-items: center;
  justify-content: center;
}
<div class="wrapper">
  <div class="centerthis">loremloremlorem</div>
</div>

Using the CSS above, the div is centered vertically, but not horizontally.

The following CSS centers the div horizontally, but not vertically:

.maingrid {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  align-items: center;
  justify-content: center;
}

.centerthis {
  align-self: center;
  justify-self: center;
}
<div class="maingrid">
  <div class="centerthis">loremloremlorem</div>
</div>


Solution

  • Instead of justify-content: center use justify-items: center.

    .wrapper {
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: 100vh;
      align-items: center;
      justify-items: center; /* adjusted */
    }
    <div class="wrapper">
      <div class="centerthis">loremloremlorem</div>
    </div>

    In your second example, you say:

    The following CSS centers the div horizontally but not vertically.

    That's because the container has no extra height. The row is the height of the content. Instead of grid-template-rows: 1fr try something like grid-template-rows: 100vh.

    .maingrid {
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: 100vh;
      align-items: center;
      justify-content: center;
    }
    
    .centerthis {
      align-self: center;
      justify-self: center;
    }
    
    body {
      margin: 0;
    }
    <div class="maingrid">
      <div class="centerthis">loremloremlorem</div>
    </div>

    More here: