CSS Subgrid

Published on

I don't know how you got here, but there's not much to look at.

This is my main blog layout but using CSS Subgrid. The header over there is it's own named column, along with the main content area. That means content can stretch arbitrarily across the grid without having to break out of it's parent container. Pretty neat!

But what does that mean in practice?

Let's take an image. Normally, an image inline in a post could only live within its parent container, like this:

But now, with CSS Subgrid, that same image can span multiple grid columns:

Subheadings and Images can span multiple columns

That's more or less the whole trick. It also can work with other tags:

Which is pretty cool, I guess? Anyway it's not easy to do without lots of oddball css. The one thing I feel like this gives up is using block layouts anywhere. Subgrids need to nest, so in order to have an element span multiple columns, it's parent needs to occupy those columns

Or do like a full width stripe thing:

It's fun to break the grid

I could also do something fun, like having a full-width code block. Here's the relevant CSS for this page:

  main {
    padding: 0;
    display: grid;
    grid-template-columns: [fullbleed-start] 1fr [header] 16rem [main-start] 66ch [main-end] 1fr [fullbleed-end];
    column-gap: 2rem;
  }

  main > header {
    grid-column: header;
  }

  main > div {
    display: grid;
    grid-template-columns: subgrid;
    grid-area: fullbleed;
  }

  main > div > * {
    grid-column: main;
  }

  img {
    margin: 2rem 0;
  }

  main > div > img.fullbleed {
    block-size: auto;
    grid-column: header / main-end;
    width: 100%;
    aspect-ratio: 16 / 9;
  }

  main > div > h2 {
    grid-column-start: header;
  }