Layering elements with CSS grid

One of my favorite little css tricks is using grid to stack elements when needed. This may be a no-duh moment for other humans, but hopefully it can help some folks out.

// The foundation
.parent {
  display: grid;
}

.first-child,
.section-child {
  grid-area: 1 / 1;
}

// Simplier example
.parent {
  display: grid;
}

.parent * {
  grid-area: 1 / 1;
}

I often use these rules for stacking in a hero, but basically any place where a background element is needed with content on top. Cards, full width call to actions, you name it. Pretty neat!

See the Pen Grid Area Hero by Glenn Weatherson (@gweatherson) on CodePen.

Link to Codepen

From there, a few positioning rules can change the content alignment. It’s not only about centered content on top of a layer underneath.

.content {
  place-self: start;
  align-self: end;
  align-items: start;
}

See the Pen Grid Area Hero (Alternative Positioning) by Glenn Weatherson (@gweatherson) on CodePen.

Link to Codepen

The older method would have been using absolute positioning and then vertically and/or horizontally centering the above element(s) using transforms or some other form of positioning. This works, but it now feels hacky and is typically more code.

Back to all Writing