Day 69: width in container queries

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.


In a media query, it’s obvious what width means. It always refers to the width of the viewport. With size container queries it’s not that obvious.

/* Kicks in when the viewport has a minimum width of 500px */
@media (min-width: 500px) {
  body {
    background-color: hotpink;
  }
}

width in a size container query queries the width of the container's content box. Let me illustrate what that means with an example.

The <section> is the container and the .card changes background color when the container has a minimum width of 500px.

<section>
  <h2>Latest news</h2>

  <div class="card">
    <h2>Hey, I'm a card!</h2>
  </div>
</section>

The <section> has an explicit width, padding, and a border. Its box-sizing property is set to the default value content-box.

section {
  box-sizing: content-box;
  container-type: inline-size;

  width: 500px;
  padding: 20px;
  border: 10px solid;
}

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

The total width of the container (<section>) is 560px (500px width + 40px padding + 20px border). The container query fires when the width without padding and border (content-box) is at least 500px, not when the total width is 500px.

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.

total width: 560px,
content-box: 500px

Hey, I'm a card!

If you change box-sizing: content-box; to box-sizing: border-box;, the total width of the container is 500px (440px width + 40px padding + 20px border). The container query still only fires when the content-box is at least 500px.

section {
  box-sizing: border-box;
  container-type: inline-size;

  width: 500px;
  padding: 20px;
  border: 10px solid;
}

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

total width: 500px,
content-box: 460px

Hey, I'm a card!

So, when we talk about width in a size container query, it always refers to the size of the content-box.

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