Skip to content

Courses / CSS3 Mastery: Beginner to Advanced / Container Queries

2,099 people viewed this

Container Queries

CSS Container Queries

Learning Objectives

  • Understand viewport queries versus container queries.
  • Create named query containers.
  • Use container size queries and container units.
  • Build reusable components that adapt to their parent.

1. What Is a Container Query?

A media query commonly responds to viewport or device conditions. A container query allows a component to respond to the size or other supported characteristics of its query container.

2. Establish a Query Container

.card-wrapper {
  container-type: inline-size;
}

Container-type: inline-size establishes an inline-size query container and applies relevant containment. The container must be an appropriate ancestor of the component being queried.

3. Write a Size Query

.product-card {
  display: grid;
  gap: 12px;
}
@container (min-width: 500px) {
  .product-card {
    grid-template-columns: 160px minmax(0, 1fr);
    align-items: center;
  }
}

When the relevant query container reaches the specified inline size, the card changes to a two-column layout.

4. Named Containers

.sidebar {
  container: sidebar / inline-size;
}
@container sidebar (min-width: 320px) {
  .widget-title {
    font-size: 1.5rem;
  }
}

Named containers let you target a particular eligible ancestor when several containers exist. A container query does not normally query an element against itself; style a descendant of the query container.

5. Container Query Units

.card-title {
  font-size: clamp(1rem, 5cqi, 2rem);
}

Container query units include cqw, cqh, cqi, cqb, cqmin and cqmax. For example, cqi is based on one percent of the query container's inline size. If no eligible container exists, container units can fall back to small viewport units.

6. Component-Responsive Design

.profile-panel {
  container-type: inline-size;
}
.profile {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
@container (min-width: 420px) {
  .profile {
    flex-direction: row;
    align-items: center;
  }
}

This component can adapt when placed in a narrow sidebar or a wider content region without relying solely on viewport width.

7. Container Queries and Media Queries Together

Use media queries for page-level changes, device preferences and viewport conditions. Use container queries when a reusable component needs to adapt to its allocated space.

Practice Exercise

Create a product card that stacks its image and details in a narrow container and places them side by side in a wide container. Reuse it in two different page regions.

Rate this course

No ratings yet — yours can be the first.

Stars show on this course. Your written note stays private.

Your stars