CSS :has() Examples

Change the layout of a grid based on the contents.

In this example we have a presentation where each slide might have, a title, a title + image or a title + 2 images.

We change the grid-template-areas accordingly.

article:has(> :is(h1, h2, h3, h4, h5, h6):only-child) {
  grid-template-areas:
    "heading heading"
    "heading heading";
}

article:has(h2 + img) {
  grid-template-areas:
    "heading heading"
    "image1 image1";
}

article:has(h2 + img + img) {
  grid-template-areas:
    "heading heading"
    "image1 image2";
}

My Cool Presentation

First Section

Second Section