This content originally appeared on Bram.us and was authored by Bramus!
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.
- Duplicate the value for the
contain
property into a CSS Custom Property named--css-contain
- 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 "https://cdn.skypack.dev/cqfill";
cqfill();
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:
This content originally appeared on Bram.us and was authored by Bramus!

Bramus! | Sciencx (2021-04-27T21:37:41+00:00) A first look at CQFill, a Polyfill for CSS Container Queries. Retrieved from https://www.scien.cx/2021/04/27/a-first-look-at-cqfill-a-polyfill-for-css-container-queries/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.