Detecting CSS features with @supports

if('registerElement' in document){ … }
CSS feature detection support in caniuse

The CSS @supports directive

The @supports directive works much alike media queries. You specify a condition, in this case a feature you want to use, and apply styles as usual. The example shows how to detect support for CSS Scroll Snap Points, which is (at the time of writing) implemented in Firefox:

@supports (scroll-snap-type:mandatory){
.scroll {
scroll-snap-type: mandatory;
...
}
}
@supports (-webkit-scroll-snap-type: mandatory) or
(-ms-scroll-snap-type: mandatory) or
(scroll-snap-type: mandatory) {
.scroll {
-webkit-scroll-snap-type: mandatory;
-ms-scroll-snap-type: mandatory;
scroll-snap-type: mandatory;
...
}
}
@supports not ((-webkit-scroll-snap-type: mandatory) or
(-ms-scroll-snap-type: mandatory) or
(scroll-snap-type: mandatory)) {
.scroll {
/* define a fallback */
...
}
}

Using CSS.supports() in JavaScript

The window.CSS.supports() functions does exactly the same thing in JavaScript. It checks whether a feature is available and gives a boolean result. Following the CSS Snap Points example from above, we could simply decide whether to we had load a polyfill by using

if(!CSS.supports("scroll-snap-type", "mandatory"){
// load polyfill
}
if(!CSS.supports("(-webkit-scroll-snap-type: mandatory) or
(-ms-scroll-snap-type: mandatory) or
(scroll-snap-type: mandatory)"){
// load polyfill
}

Happy feature detecting!

Thanks for reading. Best way to stay tuned is following us on Twitter. Comments are as always very welcome.

--

--

The tech staff of OneBitAhead GmbH, putting the web stack to work. Here to discuss daily bits & bytes. #javascript #nodejs #webcomponents #rdbms #php

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
OneBitAhead

OneBitAhead

The tech staff of OneBitAhead GmbH, putting the web stack to work. Here to discuss daily bits & bytes. #javascript #nodejs #webcomponents #rdbms #php