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 or appearance of a container. For size based container queries this is similar to a @media
query, except that it will evaluate against the size of a parent container instead of the viewport.
For style based container queries you conditionally apply styles based on the calculated value of another CSS property.
🤔 Polyfill?
A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively — What is a Polyfill?
~
Update 2021.11.26: This polyfill does not play nice with the most recent Container Queries Syntax. Instead, please use the container-query-polyfill
polyfill
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 style; /* For browsers that support Container Queries */
--css-contain: layout inline-size style; /* 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 🙂
⚠️ It’s very import to use the naming as used in the code above. The Custom Property must be named --css-contain
and the Media Query must contain the text --css-container
. If named differently, the polyfill won’t be able to pick them up.
~
Once your styles have been declared you can import the polyfill, after which it’ll do its thing:
<script src="https://unpkg.com/cqfill"></script>
If you want a local copy of CQFill, you can install it per NPM/Yarn.
npm install cqfill
import { cqfill } from "cqfill";
⚠️ I’ve noticed that loading cqfill from Skypack doesn’t seem to work unfortunately …
☝️ 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:
Leave a comment