Named vs Unnamed CSS Containers — When to Name Your Containers

Learn when to use container-name for targeted container queries versus unnamed containers that match the nearest ancestor with containment.

Container Types

Detailed Explanation

Named vs Unnamed Containers

CSS container queries can target specific containers by name or match the nearest ancestor with containment. Understanding when to use each approach is key to writing maintainable CSS.

Unnamed Container

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

@container (min-width: 400px) {
  .child { /* styles */ }
}

Without a name, @container matches the nearest ancestor that has containment. This is simple and works well for isolated components.

Named Container

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

@container card (min-width: 400px) {
  .child { /* styles */ }
}

With a name, the query only matches ancestors with that specific name. This is essential in nested scenarios.

When Names Are Essential

.outer {
  container-type: inline-size;
  container-name: outer;
}
.inner {
  container-type: inline-size;
  container-name: inner;
}

/* Targets the outer container specifically */
@container outer (min-width: 800px) {
  .widget { /* wide layout */ }
}

/* Targets the inner container specifically */
@container inner (min-width: 300px) {
  .widget { /* inner-wide layout */ }
}

Without names, both queries would match the nearest ancestor, which would always be the inner container for deeply nested elements.

Shorthand Property

You can set both type and name with the container shorthand:

.sidebar {
  container: sidebar / inline-size;
}
/* Equivalent to:
   container-name: sidebar;
   container-type: inline-size; */

Best Practice

  • Use unnamed containers for simple, non-nested components.
  • Use named containers when you have nested containment or when components are shared across different layout contexts where clarity matters.

Use Case

Reference this guide when deciding whether to name your containers. Use unnamed containers for simple single-level components and named containers when you have nested containers or need to target specific ancestors.

Try It — CSS Container Query Builder

Open full tool