Course contentsShow
← Web Development
Lesson 435 of 2,9827. Responsive DesignFree lesson

Named Containers

Assigning container-name to target specific containers in queries when multiple containment contexts exist.

Named Containers

What you'll learn: How to give your containers unique names so you can write specific container queries for each one when you have multiple containment contexts on the same page.

The Problem with Anonymous Containers

So far, you've set up container contexts with container-type, but what happens when you have multiple containers on the same page? If you don't name them, every element inside any container will respond to the same container queries. That's like having multiple rooms in your house but only one thermostat controlling all of them—sometimes you need individual control.

Naming Your Containers

The container-name property lets you assign a unique identifier to each container context:

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

.main-content {
  container-type: inline-size;
  container-name: main;
}

Now each container has its own identity: one is called "sidebar" and the other is "main".

Targeting Named Containers

When you write a container query, you can specify which container you're querying:

@container sidebar (min-width: 300px) {
  .widget {
    font-size: 1.2rem;
  }
}

@container main (min-width: 600px) {
  .widget {
    font-size: 1.5rem;
  }
}

Even if both containers have .widget elements inside them, each responds only to its own container's width. The sidebar's widgets and the main area's widgets can adapt independently.

Think of It Like Room Labels

Imagine apartment buildings where every unit is just numbered "Apartment." Confusing! Named containers are like giving each apartment a unique number—suddenly you can deliver mail to the right place.

Key Takeaway: Use container-name to give each container context a unique identifier, allowing you to write targeted container queries that affect only specific containers even when multiple containment contexts exist on the same page.