A simple way to programmatically detect support for cascade layers

by Ryan Geyer —

I recently needed to be able to programmatically test if a browser supports the relatively new @layer Cascade Layers CSS feature (in my opinion, one of the most exciting and underrated recent additions to CSS).

However, I quickly ran up against a big problem: @support queries don’t work for at-rules like @layer! I’d love to be able to do something like what’s suggested in this issue:

const doesSupportCascadeLayers = window.CSS.supports("at-rule(@layer)");

But currently, no dice. After a lot of searching around, I almost thought I was out of luck, but then I discovered that Cascade Layer support also comes along with the presence of some global classes which we can test for the existence of on the window!

This works like a charm:

const doesSupportCascadeLayers = "CSSLayerStatementRule" in window;

Unfortunately, I don’t think there’s any way to detect @layer support in pure CSS, but this was thankfully enough to satisfy my needs.