MDN self-hosted library · e01.org

CSS container queries

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>
css
.post {
  container-type: inline-size;
}
css
/* Default heading styles for the card title */
.card h2 {
  font-size: 1em;
}

/* If the container is larger than 700px */
@container (width > 700px) {
  .card h2 {
    font-size: 2em;
  }
}
css
.post {
  container-type: inline-size;
  container-name: sidebar;
}
css
@container sidebar (width > 700px) {
  .card {
    font-size: 2em;
  }
}
html
<div id="container">
  <p>I'm in the container.</p>
  <p>I'm also in the container.</p>
</div>
<p>I'm not in the container.</p>
css
#container {
  container-name: my-container;
}
css
@container my-container {
  p {
    background-color: lime;
    font-size: 1.3rem;
    width: 50vw;
    padding: 0.5rem;
    font-family: sans-serif;
  }
}
css
.post {
  container: sidebar / inline-size;
}
css
@container (width > 700px) {
  .card h2 {
    font-size: max(1.5em, 1.23em + 2cqi);
  }
}
css
.card {
  display: grid;
  grid-template-columns: 2fr 1fr;
}
css
@media (width <= 700px) {
  .card {
    grid-template-columns: 1fr;
  }
}