GoogleChromeLabs / container-query-polyfill

A polyfill for CSS Container Queries
https://npm.im/container-query-polyfill
Apache License 2.0
1.13k stars 50 forks source link

Container Query Polyfill

Please note that this polyfill is now in maintenance mode, as of Nov, 2022. We are not planning to add more features or enhancements.


A small (9 kB compressed) polyfill for CSS Container Queries using ResizeObserver and MutationObserver supporting the full @container query syntax:

Browser Support

Getting Started

Installation

npm install --save container-query-polyfill

Alternatively, you can use it directly from a CDN:

<script src="https://cdn.jsdelivr.net/npm/container-query-polyfill@1/dist/container-query-polyfill.modern.js"></script>

For the best user experience, it's recommended that you initially only use the polyfill for content below-the-fold and use @supports queries to temporarily replace it with a loading indicator until the polyfill is ready to display it:

@supports not (container-type: inline-size) {
  .container,
  footer {
    display: none;
  }

  .loader {
    display: flex;
  }
}

You can view a more complete demo here. On sufficiently fast networks and devices, or devices that natively support Container Queries, this loading indicator will never be displayed.

Note Keep in mind that this technique effectively limits impact on FID and CLS, potentially at the expense of LCP. You may see regressions in the latter as a result, particularly on lower end devices or in poor network conditions.

Limitations

Supporting browsers without :where()

The polyfill uses the CSS :where() pseudo-class to avoid changing the specificity of your rules. This pseudo-class is relatively new, however. If you need to support browsers without it, you will need to append the dummy :not(container-query-polyfill) pseudo-class to the originating element of every selector under a @container block:

Before After
```css @container (min-width: 200px) { #foo { /* ... */ } .bar { /* ... */ } #foo, .bar { /* ... */ } ul > li { /* ... */ } ::before { /* ... */ } } ``` ```css @container (min-width: 200px) { #foo:not(.container-query-polyfill) { /* ... */ } .bar:not(.container-query-polyfill) { /* ... */ } #foo:not(.container-query-polyfill), .bar:not(.container-query-polyfill) { /* ... */ } ul > li:not(.container-query-polyfill) { /* ... */ } :not(.container-query-polyfill)::before { /* ... */ } } ```

This is to ensure the specificity of your rules never changes (e.g. while the polyfill is loading, or on browsers with native support for container queries). On browsers without :where() supports, rules without the dummy will be ignored.

ResizeObserver Loop Errors

When using the polyfill, you may observe reports of errors like ResizeObserver loop completed with undelivered notifications or ResizeObserver loop limit exceeded. These are expected, and may safely be ignored.

License

Apache 2.0