Search code examples
csscss-grid

CSS Grid - Set item width on hover


I am building a simple CSS grid layout that looks like this...

.container {
  display:grid;
  grid-template-columns:1fr 1fr 1fr 1fr;
}

.col1 {
  padding:20px;
  background:red;
  color:white;
  text-align:center;
}

.col2 {
  padding:20px;
  background:green;
  color:white;
  text-align:center;
}

.col3 {
  padding:20px;
  background:blue;
  color:white;
  text-align:center;
}

.col4 {
  padding:20px;
  background:gray;
  color:white;
  text-align:center;
}
<div class="container">

  <div class="col1">
    Column 1
  </div>

  <div class="col2">
    Column 2
  </div>

  <div class="col3">
    Column 3
  </div>

  <div class="col4">
    Column 4
  </div>

</div>

I am trying to make it so that when any of the columns are hovered over, they change width so that the hovered column takes up 2fr.

I know with flexbox I can set the width of the item in the item itself, but with grid I set item widths on the container.

Is there a way to set them on the items?


Solution

  • You can do this with the grid-column property. It takes two integers, the starting and ending tracks (e.g. 1/3). The hitch is, you can't expand the last column without some extra work, because it jumps to the next line, out of range of the initial hover zone:

    EDIT: As per the comment below, I've updated the hover code to be: grid-column: span 2; This is the same as "start at your beginning track and span 2 columns." This is a bit cleaner, in that it allows you to set a single style rule for every column. I've also added a :not(.col4) to the rule to avoid the aforementioned issue of the column jumping to the next line. Of course, you need to give each column the same "col" class for this to work:

    .container {
      display:grid;
      grid-template-columns:1fr 1fr 1fr 1fr;
    }
    
    .col1 {
      padding:20px;
      background:red;
      color:white;
      text-align:center;
    }
    
    .col2 {
      padding:20px;
      background:green;
      color:white;
      text-align:center;
    }
    
    .col3 {
      padding:20px;
      background:blue;
      color:white;
      text-align:center;
    }
    
    .col4 {
      padding:20px;
      background:gray;
      color:white;
      text-align:center;
    }
    
    .col:not(.col4):hover{
       grid-column: span 2;
    }
    <div class="container">
    
      <div class="col1 col">
        Column 1
      </div>
    
      <div class="col2 col">
        Column 2
      </div>
    
      <div class="col3 col">
        Column 3
      </div>
    
      <div class="col4 col">
        Column 4
      </div>
    
    </div>