Day 65: using the em unit 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.


Relative units used in container queries work differently than relative units in media queries.

If you use em in a media query, the font-size of the <body>, <html>, or any other element on the page doesn't matter. That's because relative length units in media queries are based on the initial value, which means that units are never based on results of declarations. em in a media query is relative to the font-size, defined by the user agent or the user’s preferences.

/* 
  The font size of both <body> and <html> is 40px,
  the media query doesn't fire at 2560px (40 * 64),
  but at 1024px (16 * 64) (assuming that the base 
  font size in the browser is 16px).
*/

html, body {
  font-size: 40px;
}

@media (min-width: 64em) {
  body {
    background: aqua;
  }
}

With container queries that's different. Relative length units are evaluated based on the computed values of the query container.

The container query in the following example fires at 512px (32 * 16 = 512) because the font size of the container is 16px.

section {
  font-size: 16px;
  container: wrapper / inline-size; 
}

.card {
  background-color: yellow;
}

@container wrapper (min-width: 32em) {
  .card {
    background-color: hotpink;
  }
}
<section>
  <h2>Latest news</h2>

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

You can grab and resize the <section> by clicking and dragging it in the bottom right corner.

Latest news

Hey, I'm a card!

If you change the font size of the container to 26px, the media query fires at 832px (32 * 26 = 832)

.large {
  font-size: 26px;
}
<section class="large">
  <h2>Latest news</h2>

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

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