Day 59: naming containers

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


When you add a container query, it will look for the nearest ancestor container, by default. If you have multiple nested containers or if you just want to make sure that your query uses the right container, you can name containers and query them specifically.

Let's say, we have 2 size containers, .wrapper and <section>.

<div class="wrapper">
  <section>
    <h2>Latest news</h2>

    <div class="card">
      <h2>Hey, I'm a card!</h2>
    </div>
  </section>
</div>
/* That's our outer size container. */
.wrapper {
  container-type: inline-size;
}

/* That's our inner size container. */
section {
  width: 50%;
  container-type: inline-size;
}

/* Default styles for the card. */
.card {
  background-color: yellow;
  border: 5px solid;
}

/* Container query */
@container (min-width: 500px) {
  .card {
    background-color: hotpink;
  }
}

By default, the container query watches the width of the closest size container, <section>. You can grab and resize the <section> by clicking and dragging it in the bottom right corner. The background color of the .card changes as soon as the width of the parent section hits 500px.

Latest news

Hey, I'm a card!

By naming the container and using that name in the query, you can target a specific container.

/* That's our outer size container. */
.wrapper {
  container-type: inline-size;
  container-name: wrapper;
}

/* That's our inner size container. */
section {
  container-type: inline-size;
}

/* The query watches the width of the outer size container (.wrapper) */
@container wrapper (min-width: 500px) {
  .card {
    background-color: hotpink;
  }
}

You can grab and resize the .wrapper by clicking and dragging it in the bottom right corner. The background color of the .card changes as soon as the width of the .wrapper is lower than 500px.

Latest news

Hey, I'm a card!

See on CodePen

Further reading

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS