CSS Container Queries example

CSS container queries example. @container watches the component box, not the viewport. compact, split, and open from the same markup.

The problem

History of responsive design is a history of the viewport. The viewport is the window, and the window is the viewport. The viewport is the only thing that can be queried. But what if you want to query a box? What if you want to query a component? What if you want to query a container?

The method

@container is a new CSS rule that allows you to query the size of a container instead of the viewport. It works by defining a container with container-type and then using @container to applys based on the container's size.

The stage

container

The box, not the window

This line waits for 420px. The viewport stayed put.

type uses cqi

The example


  

The box, not the window

This line waits for 420px. The viewport stayed put.

type uses cqi

.frame {
  box-sizing: border-box;
  width: min(100%, 22rem);
  min-width: 16rem;
  max-width: 100%;
  resize: horizontal;
  overflow: auto;
  container-type: inline-size;
  container-name: frame;
}

.unit {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin: 0;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 12px;
  background: #fff;
  font-family: system-ui, sans-serif;
}

.unit-media {
  display: grid;
  place-items: center;
  min-height: 6rem;
  border-radius: 8px;
  background: #f2f2f2;
}

.unit-media::after {
  content: "compact";
  font-weight: 700;
}

.unit-title {
  margin: 0;
  font-size: 1.25rem;
}

.unit-body,
.unit-meta {
  margin: 0;
  color: #666;
}

@container frame (min-width: 420px) {
  .unit {
    flex-direction: row;
    align-items: center;
  }

  .unit-media {
    width: 8rem;
    height: 8rem;
  }

  .unit-media::after {
    content: "split";
  }
}

@container frame (min-width: 620px) {
  .unit-media {
    width: 12rem;
    height: 12rem;
  }

  .unit-media::after {
    content: "open";
  }
}

All Web API labs

  • CSS overflow carousel example
  • CSS Anchor Positioning example
  • Customizable select example