Search code examples
cssflexboxcss-grid

How can I get a 3 columns by 2 rows symmetrical layout with 5 elements using CSS grid?


I have obtained the layout below using CSS flexbox:

* {
  font-family: Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}

.my-grid {
  list-style-type: none;
  padding: 0;
  margin: 0 auto;
  display: flex;
  width: 162px;
  flex-wrap: wrap;
}


.my-grid li {
  border: 1px solid rgba(0, 0, 0 , 0.125);
  background:#c00;
  color: #fff;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 2px;
} 

.my-grid li:nth-child(4),
.my-grid li:nth-child(5) {
  width: 77px;
}
<ul class="my-grid">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

However, my attempt to get the same result using CSS grid has failed. All I got was:

* {
  font-family: Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}

.my-grid {
  width: 160px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: repeat(2, 50px);
  grid-gap: 5px;
  list-style-type: none;
  margin: 0 auto;
  padding: 0;
}


.my-grid li {
  border: 1px solid rgba(0, 0, 0 , 0.125);
  background:#c00;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
} 
<ul class="my-grid">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

I would like to be able to achieve the result you can see in the first snippet, by using CSS grid, with as few lines as possible. (I find CSS grid generally very flexible and elegant).

Is that possible? What am I missing?


Solution

  • Just tell the children to span 2 columns in a 6 column grid by default and the wider ones to span 3 columns..

    * {
      font-family: Arial, Helvetica, sans-serif;
      box-sizing: border-box;
    }
    
    .my-grid {
      width: 160px;
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      grid-template-rows: repeat(2, 50px);
      grid-gap: 5px;
      list-style-type: none;
      margin: 0 auto;
      padding: 0;
    }
    
    .my-grid li {
      border: 1px solid rgba(0, 0, 0, 0.125);
      background: #c00;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      grid-column: span 2;
    }
    
    .my-grid li:nth-last-child(2),
    .my-grid li:nth-last-child(1) {
      grid-column: span 3
    }
    <ul class="my-grid">
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>