Ray Knight GenUI Software Engineer

Ray Knight practices software engineering at GenUI.

The following is a copy of an article originally posted here: https://medium.com/@arrayknight/css-layering-using-display-grid-ad32463e3b8e

I was playing around with CSS grid and associated properties and happened across an approach that solved a common scenario: when content should be layered on top of other content, but you want the parent height to be stable.

Approach

The basic styles are very simple:

.parent {
  display: grid;
  grid-template-areas: "content";
}.child {
  grid-area: content;
}

You don’t have to use the name “content” it can be anything that is meaningful to you. Ex: area, content, space, stack, etc.

Benefits

This will setup a layering area with content driven height that doesn’t require positioning, floats, pseudo elements or javascript. Unlike position: absolute each child element’s height pushes the parent height, the largest at any given point setting the overall height. The layering is simply down to DOM order, but can easy be updated with z-index like normal.

Use Cases

Tab Content

See the Pen CSS Grid Tabs by Ray Knight (@ArrayKnight) on CodePen.

Notice that the content area for the tab content doesn’t change in height. This means that if you switch tabs, the remaining page content doesn’t jump up and down. This is due to the largest amount of content (third tab) setting the height of the parent dynamically, no hacks or scripting.

Transitioning Content

See the Pen CSS Grid Carousel by Ray Knight (@ArrayKnight) on CodePen.

Again no need for positioning or z-indexing. It really simplifies layout and not having to calculate height or set a fixed aspect ratio.

And more…

This approach is so easy that it could be used in many more scenarios. It provides a nice, relatively non-invasive (style overrides-wise) way to allow for a wrapper component to position a loader over some content/component.

Support

CSS Grid is not 100% supported, so be sure to implement a polyfill or an alternative solution for those browsers.

Related Articles

Eliminate Redux Boilerplate with Hooks-for-Redux (H4R)

Hooks for Redux eliminates the repetition without sacrificing any power.

How to use .env variables in package.json

A simple cross platform way to utilize secrets in build scripts without writing shell scripts.

Building a Drum Sequencer with React Hooks

GenUI Engineer Rob Brennan takes us through the intriguing use of React Hooks to build a Drum Sequencer in his teck talk.