skip to Main Content

Trying to search this is impossible — every answer is about a slightly different problem, which is making it so all the rows in a single column are the same height (i.e. the same height as the tallest cell in that column). They say to add grid-auto-rows: 1fr to the grid container. That’s true and works, but isn’t what I’m describing.

Here, I’ll send a sample code that demonstrates what I’m talking about. I wanted the "aaa" cell to be the same height as the "BBB" cell, for the "ccc" cell to be the same height as the "DDD" cell, … .

.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
  grid-auto-rows: 1fr;
  margin: 8px 0;
  width: 600px;
  gap: 2px;
  align-items: center;
}

.grid-item {
  border: 1px solid grey;
  background-color: #fea;
}

.bigger-text {
  font-size: 21px;
  line-height: 36px;
}
<div class="grid-container">
  <div class="grid-item">aaa</div>
  <div class="grid-item bigger-text">BBB</div>
  <div class="grid-item">ccc</div>
  <div class="grid-item bigger-text">DDD</div>
  <div class="grid-item">eee</div>
  <div class="grid-item bigger-text">FFF</div>
</div>

2

Answers


  1. The issue is solely caused by align-items: center which sets the height to the content and then vertically centering the item.

    You can use `flexbox to center the text if you need:

    .grid-container {
      display: grid;
      grid-template-columns: 1fr 2fr;
      margin: 8px 0;
      width: 600px;
      gap: 2px;
    }
    
    .grid-item {
      border: 1px solid grey;
      background-color: #fea;
      /* vertically centers text */
      display: flex;
      align-items: center;
    }
    
    .bigger-text {
      font-size: 21px;
      line-height: 36px;
    }
    <div class="grid-container">
      <div class="grid-item">aaa</div>
      <div class="grid-item bigger-text">BBB</div>
      <div class="grid-item">ccc</div>
      <div class="grid-item bigger-text">DDD</div>
      <div class="grid-item">eee</div>
      <div class="grid-item bigger-text">FFF</div>
    </div>
    Login or Signup to reply.
  2. if you want the cells in a css grid row to have the same height across columns, you can set the align-self property for each item to stretch. this will make each item in the row stretch to match the height of the tallest item in that row. here is the modified code:

    .grid-container {
      display: grid;
      grid-template-columns: 1fr 2fr;
      margin: 8px 0;
      width: 600px;
      gap: 2px;
    }
    
    .grid-item {
      border: 1px solid grey;
      background-color: #fea;
      align-self: stretch;
    }
    
    .bigger-text {
      font-size: 21px;
      line-height: 36px;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search