Search code examples
csscss-grid

How to make a grid item stretch to full width if next element is hidden?


guys. I'm trying to understand CSS Grid and found a behaviour I thought would be simple but turned out to be a little complicated. I need to follow a 12-column layout a have a row with 2 elements but I need these elements to fill 100% of the width if it is the single element.

I tried to use auto-fit and it almost did the job but I couldn't find a way to explicitly set 12 columns this way.

Here's a snippet of my code:

<div class="autofit">
  <div class="content"></div>
  <div class="banner"></div>
</div>


.autofit { 
            display:grid; 
            grid-template-columns: repeat(12, minmax(0, 1fr));
            grid-gap: 20px;
            text-align: center; 
    } 

   .autofit .content{  
            grid-column: 1/9;
   }
   .autofit .banner { 
            grid-column: 10/-1; 
    }

This way the grid works as expected but if I delete the .banner element the .content doesn't stretch to fill the available space ):


Solution

  • Use :only-child to define and extra rule:

    .autofit {
      display: grid;
      grid-template-columns: repeat(12, minmax(0, 1fr));
      grid-gap: 20px;
      text-align: center;
      margin:5px;
    }
    .autofit > *{
      height:20px;
    }
    .autofit .content {
      grid-column: 1/9;
      background:red;
    }
    
    .autofit .banner {
      grid-column: 10/-1;
      background:blue;
    }
    
    .autofit > :only-child{
      grid-column: 1/-1;
    }
    <div class="autofit">
      <div class="content"></div>
      <div class="banner"></div>
    </div>
    
    <div class="autofit">
      <div class="content"></div>
    </div>
    
    <div class="autofit">
      <div class="banner"></div>
    </div>