Browser Compatibility Made Easy: The @supports Rule in CSS
Ever stumbled upon a cool CSS feature you're dying to use but worried about browser compatibility?
Enter the @supports
rule, our conditional friend in CSS.
Let's look at how you can leverage it. 👇
What is @supports?
In simple terms, the @supports
rule, also known as "Feature Queries", is your conditional check in CSS.
It checks if the browser knows a particular property-value combo.
If it does, great! The styles within our @supports
block come to life. If not, they are ignored.
As always I think this is better with an example:
/* structure of @supports @supports (property: value) { ✨ styles that show if the browser knows the property-value combo. */ } */ /* Now testing with a not-so-widely supported property*/ @supports (text-wrap: balance) { h1 { text-wrap: balance; } }
So as you can see, we can test to see if something is available before safely applying it.
Logical Operators
Our @supports
has some logic up its sleeve:
- and: Both property-value conditions have to be available.
- or: One available property value combination is enough.
- not: Checking if something does "not" support this.
Again, let's look at it in action with some newer/less supported properties you can try in different browsers:
/* Both grid and subgrid? */ @supports (display: grid) and (grid-template-columns: subgrid) { /* Styles 💅 */ } /* Dynamic View Height or text-wrap balance? Either way, we're good. */ @supports (text-wrap: balance) or (height: 100dvh) { /* Styles 💅 */ } /* No grid? No problem! */ @supports not (text-wrap: balance) { /* Styles 💅 */ }
Real-World Uses
- Progressive Enhancement: Ensure your trying out the latest features without breaking things for everyone.
- Ditch JS Detectors: Remember using JavaScript libs like Modernizr for feature checks? With
@supports
, we can keep it all in CSS. - Clean code: Organize your stylesheet by feature support.
Potential issues
- The Paradox: If a browser hasn't heard of
@supports
, it won't care about the styles inside, even if it knows the actual CSS trick. - Good Old IE: Internet Explorer (yes, it still exists) doesn't vibe with
@supports
. So, keep that in mind if your audience includes this vintage crowd.
Wrapping up
The @supports
rule is like that multi-tool you never knew you needed.
Go out there and start experimenting. 🧪
Happy coding! ⚡️
Follow me on Twitter or connect on LinkedIn.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉