Search code examples
htmlcsscss-grid

CSS Grid: Center Content And Left Align Text


I think there should be an easy solution here but I can't quite find it. I want to re-create something like the following image:

enter image description here

Notice how the item and quantity rows are centered below the details title, but the text contained within them is left-aligned. Here is my attempt:

.grid-container {
  background: gray;
  display: inline-grid;
  justify-items: center;
  align-content: center;
  grid-template-columns: 1fr 1fr;
  padding: 10px;
}

.details {
  font-weight: bold;
  grid-column: span 2;
}

.info {
  text-align: left;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="./style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="grid-container">
      <div class="details">Details</div>
      <div class="info">Item</div>
      <div class="info">Beans</div>
      <div class="info">Quantity</div>
      <div class="info">41</div>
    </div>
  </body>
</html>

but you can see that, although the content is centered correctly, the text is not left-justified. Is there a way to do this with CSS grid?

Thank you.


Solution

  • Simply remove justify-items: center (this justify each item's content to the center of that item) and set justify-self: center for .details.

    Try it:

    .grid-container {
      background: gray;
      display: inline-grid;
      align-content: center;
      grid-template-columns: 1fr 1fr;
      padding: 10px;
    }
    
    .details {
      font-weight: bold;
      grid-column: span 2;
      justify-self: center;
    }
    <div class="grid-container">
      <div class="details">Details</div>
      <div class="info">Item</div>
      <div class="info">Beans</div>
      <div class="info">Quantity</div>
      <div class="info">41</div>
    </div>