A great and powerful way to check if a CSS feature is available is to use the CSS.supports
JavaScript function:
if (CSS && CSS.supports && CSS.supports("position", "sticky")) {
// awesome: position:sticky is supported on this browser!
} else {
// fallback: I cannot rely on position:sticky!
}
I hope this answers your question, but I think it's worth mentioning that if you're tempted to use CSS.supports()
you should at least consider responding to a lack of feature just using CSS alone. While JavaScript is a great way to make dynamic changes to a page, you often don't need it to have your page respond to a lack of a feature. This is especially for CSS features like sticky.
E.g.
/*
...
Basic styles for old browsers that don't support sticky go here.
...
*/
@supports (position:sticky) {
/* Overrides to the above styles for modern "sticky" browsers go here */
}
And even then, you often don't even need to go this fancy. For example, let's say you have a nav bar that you would like to be position:sticky
if possible, but otherwise just position:absolute
. Even though some browsers don't understand sticky
, you can say:
.my-nav-bar {
/* The fallback goes first */
position: absolute;
/* This 'enhancement' is ignored if not understood, */
/* but overrides the previous value if the browser supports it. */
position: sticky;
top: 50px;
/* ... etc ... */
}