CSS Grid, When cell hidden, expand other cells

Viewed 79

I have a simple playout:

.mainGrid {
  display: grid;
  grid:
    'filterstatus filterowner filtersearch filterbutton' 1fr /
      1fr 1fr 3fr 90px;

  column-gap: 1em;
}

When filterowner is removed from the DOM, there is a big hole of course in the display.

In CSS Grid can I say "when filterowner is hidden, don't leave a big hole, spread out the space between the others".

enter image description here

1 Answers

This seems like a 1-dimensionnal issue. Grid is commonly use for 2-dimensionnal space rendering. When using this kind of setup using the Flexbox approach seems like a better alternative.

Here is an example of the solution using Flexbox :

.mainGrid {
  display: flex;
}

.mainGrid > div {        
    flex-grow:1;
    margin-left: 0.5em;
    margin-right: 0.5em;
    
    &:first-child{
      margin-left:0; 
    }
    &:last-child {
      margin-right:0;
    }
    
    &.filtersearch {
      flex-grow:3;
    }
    
    &.filterbutton {
      min-width:90px    
    }
  }
}

To solve your issue we are using the Flex property flex-grow. This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.

If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least).

This means by removing an element, the "filterowner" in your case, the remaining div will take the available space left accordingly.

Related