Search code examples
csscss-gridvertical-alignment

CSS Grid styling question using span - changes when using align-self


I have a grid where I have two columns and three rows, but the first column spans all 3 rows. The first column contains text, the second column contains 3 lines of text, one per row.

I want the height of column 1 to match the height of column 2 based on the background color of the grid content items.

This works fine if I'm happy to have the left-hand column aligned at the top of the 3 rows. But when I try to make it aligned vertically, using align-self, the background color shrinks to cover just the single row.

Perhaps the JSFiddle will say it more clearly than my description.

HTML:

<div class="wrapper">

  <div class="box title1">Text</div>
  <div class="box">Question 1</div>
  <div class="box">Question 2</div>
  <div class="box">Question 3</div>

  <div class="wide">&nbsp;</div>

  <div class="box title2">Text</div>
  <div class="box">Question 1</div>
  <div class="box">Question 2</div>
  <div class="box">Question 3</div>

</div>

CSS:

body {
  margin: 20px;
  font-family: "Garamond", "Times New Roman", serif;
}

.box {
  background-color: lightgrey;
  padding: 5px;
}

.wrapper {
  display: grid;
  grid-template-columns: 8em 8em;
}

.wide {
  grid-column: span 2;
}

.title1 {
  grid-row: span 3;
  font-size: 150%;
  font-weight: bold;
}

.title2 {
  grid-row: span 3;
  align-self: center;
  font-size: 150%;
  font-weight: bold;
}

Link to JSFiddle

How can I get the label aligned vertically but also have the background color height matched? I have tried adding attributes like "height:100%;" to the second title, but everything breaks in slightly different way. I am using Firefox but of course I want a cross-browser solution as far as reasonably possible.


Solution

  • Make the element display:flex and then align-items:center

    body {
      margin: 20px;
      font-family: "Garamond", "Times New Roman", serif;
    }
    
    .box {
      background-color: lightgrey;
      padding: 5px;
    }
    
    .wrapper {
      display: grid;
      grid-template-columns: 8em 8em;
    }
    
    .wide {
      grid-column: span 2;
    }
    
    .title1 {
      grid-row: span 3;
      font-size: 150%;
      font-weight: bold;
    }
    
    .title2 {
      grid-row: span 3;
      display: flex;
      align-items: center;
      font-size: 150%;
      font-weight: bold;
    }
    <div class="wrapper">
    
      <div class="box title1">Text</div>
      <div class="box">Question 1</div>
      <div class="box">Question 2</div>
      <div class="box">Question 3</div>
    
      <div class="wide">&nbsp;</div>
    
      <div class="box title2">Text</div>
      <div class="box">Question 1</div>
      <div class="box">Question 2</div>
      <div class="box">Question 3</div>
    
    </div>