<< back to the blog

Height-Retaining Tabs Component Using CSS Grid

When creating UI components for the web, you want to avoid jumping content where one component pushes another away. However, this is not always as easy as it seems.

A Simple Tabs Implementation

Take a tabs component as an example. You have multiple content containers and if you want to avoid jumping of the content you need to make sure that the whole component is large enough to contain the largest of the content containers.

Using CSS Grid

Until now, we resorted to using JavaScript to determine the maximum height of the content and setting it on the component. But with the dawn of CSS Grid there is an easier pure CSS solution to the problem. The trick is to put all content containers into one CSS Grid cell. The grid will then make sure that the cell is big enough for every content container.

.tabs__content-wrapper {
  display: grid;
}

.tabs__content {
  grid-column-start: 1;
  grid-row-start: 1;
  visibility: hidden;
}

.tabs__content.active {
  visibility: visible;
}
 

Browser Support

Even though the browser support for CSS grid is still mediocre, we can utilise @supports to gracefully degrade to the original solution without height retainment.

@supports (display: grid) {
.tabs__content-wrapper {
display: grid;
}

.tabs__content {
grid-column-start: 1;
grid-row-start: 1;
display: block;
visibility: hidden;
}

.tabs__content.active {
visibility: visible;
}
}

Other Usages

The same solution also works for similar use cases where I want to dynamically switch the content but retain the overall height like details containers or fading from one component into another.

<< back to the blog