Codectionary / Developer documentation / CSS

Container Queries

Container queries let an element style itself based on the size of its containing element, rather than the viewport. This solves a problem media queries never could: a truly reusable component that looks right whether it is placed in a narrow sidebar or a wide main content area. Declare a container with container-type, then respond to it with @container.

Syntax

container-type: inline-size;
@container (min-width: 400px) { }

Examples

Making a Container Queryable

Establishing an element as a query container for its descendants.

.card-wrapper {
  container-type: inline-size;
  container-name: card; /* optional, lets you target a specific container */
}

Responding to Container Size

Styling a card differently depending on how much space its container actually has.

.card {
  display: flex;
  flex-direction: column;
}

@container card (min-width: 400px) {
  .card {
    flex-direction: row; /* switches to a horizontal layout once the CONTAINER is wide enough */
  }
}

Parameters and values

  • container-type (inline-size | size | normal): Establishes an element as a query container
  • container-name (string): Optional name to target a specific container with @container
  • @container (at-rule): Applies styles conditionally based on the named container's size

Best practices

  • Use container queries for reusable components that need to adapt based on where they are placed, not just overall screen size
  • Set container-type on the direct parent of the element you actually want to style - an element cannot query its own container-type
  • Use container-name to disambiguate when nested containers exist and you need @container to target a specific one
  • Container queries and media queries are complementary, not competitors - use media queries for page-level layout and container queries for component-level layout

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation