Day 90: scoped styles 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.


Rules within a container query only apply to descendants of that container.

If you write a media query and you put rules in the media block, the rules apply to the entire document.

@media (min-width: 1024px) {
  * {
    outline: 4px solid 
  }
}

If you write a container query and you put rules in the container block, the rules only apply to descendants of the container.

<div data-sample="demo">
  <h2>A quote</h2>
  <blockquote>“What came first – the music or the misery? Did I listen to the music because I was miserable? Or was I miserable because I listened to the music? Do all those records turn you into a melancholy person?”</blockquote>
</div>
[data-sample] {
  container-type: inline-size;
}

@container (min-inline-size: 240px) {
  * {
    border: 8px dotted fuchsia;
  }
}

A quote

“What came first – the music or the misery? Did I listen to the music because I was miserable? Or was I miserable because I listened to the music? Do all those records turn you into a melancholy person?”

If you have nested containers, the styles apply to all applicable containers.

main,
[data-sample] {
  container-type: inline-size;
}

@container (min-inline-size: 240px) {
  * {
    border: 8px dotted fuchsia;
  }
}

This can cause a lot of confusion. I guess, that's one reason why it's advised to name containers.

main,
[data-sample] {
  container-type: inline-size;
}

[data-sample] {
  container-name: demo;
}

@container demo(min-inline-size: 240px) {
  * {
    border: 8px dotted fuchsia;
  }
}

A quote

“What came first – the music or the misery? Did I listen to the music because I was miserable? Or was I miserable because I listened to the music? Do all those records turn you into a melancholy person?”

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