CodeBlanks Logo Icon CodeBlanks

Container queries

CSS course · Advanced · Lesson 20/52

Learn the @container rule.

What is @container?

Media queries watch the screen width; but a component's real space is the box it lives in. The @container rule changes styles based on the width of the surrounding container.

First you mark the container with container-type: inline-size. Then you write @container (min-width: 400px) to apply styles once the container passes 400 pixels. The component now listens to its container, not the screen.

container-type: inline-size

To turn an element into a container, you set the container-type property. The most common value is inline-size; it opens the container's inline (width) axis to queries.

Once declared, the element becomes a measurement source for descendant components. A component reads the width around it and adjusts its styles accordingly.

Exercise Switch padding with a container query

Give the .panel selector container-type: inline-size. Then, inside an @container (min-width: 320px) query, set padding: 24px on the .panel-in sub-selector. The panel shows less padding in a narrow container and more in a wide one.

Show example solution
/* open the panel container */
/* more padding in wide containers */
.panel {
  container-type: inline-size;
}
@container (min-width: 320px) {
  .panel-in {
    padding: 24px;
  }
}

Test yourself

  1. Which value opens a container for container queries?

    • display: container
    • container-name: main
    • container-type: inline-size
    • position: container
    Show answer

    container-type: inline-size — Correct. container-type: inline-size opens the container's width to queries.

  2. Write the container-type property

    .panel {
      ____: inline-size;
    }
    Show answer
    .panel {
      container-type: inline-size;
    }
  3. Match container parts

    @container
    Query block
    container-type
    Opens container
    inline-size
    Measures width
    min-width
    Threshold clause

All lessons in Advanced