A first look at CQFill, a Polyfill for CSS Container Queries

Written by / Original link on Apr. 27, 2021

Jonathan Neal just announced that he has been working on a polyfill for CSS Container Queries. Let’s take a look at how it works …

🤔 Container Queries?

Container Queries allow authors to style elements according to the size of a container. This is similar to a @media query, except that it evaluates against a container instead of the viewport.



Unfortunately the polyfill is not a simple drop-in that will work with your existing CSS code. This is because rendering engines that don’t support Container Queries will discard those specific statements and declarations.

To work around this, the polyfill requires you to duplicate some CSS with an alternative syntax.

  1. Duplicate the value for the contain property into a CSS Custom Property named --css-contain
  2. Duplicate the @container rule as an @media rule bearing the text --css-container

Like so:

/* Create a Container Root */
.container {
  contain: layout inline-size; /* For browsers that support Container Queries */
  --css-contain: layout inline-size; /* For the polyfill to use */
/* Container Query */
@container (min-width: 700px) { /* For browsers that support Container Queries */
  .contained {
    /* … */

@media --css-container and (min-width: 700px) { /* For the polyfill to use */
  .contained {
    /* … */

As those duplicated rules are valid CSS, browsers won’t discard them and the polyfill can pick them up 🙂


Once your styles have been declared you can import the polyfill and call it:

import { cqfill } from "";


If you want a local copy of CQFill, you can install it per NPM/Yarn.

npm install cqfill

☝️ When using Next.js or PostCSS you don’t even need to call the polyfill, as the CQFill repo includes plugins for those.


Here’s my original demo, adjusted to include the polyfill:

See the Pen CSS Container Queries Demo (with Polyfill) by Bramus (@bramus) on CodePen.

Great work Jonathan, works like a charm!

CQFill: CSS Container Queries Polyfill (GitHub) →


🔥 Like what you see? Want to stay in the loop? Here's how:

bram bram bram tutorialzine bram

« Create a color theme with CSS Relative Color Syntax, CSS color-mix(), and CSS color-contrast() - Running PHP code in parallel, the easy way »