Skip to main content

Native CSS Feature Detection With @supports

By Craig Buckler

Blogs

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

Consider the following CSS snippet:

 .blur-text { color: transparent; text-shadow: 0 0 5px #000; } 

Any element with a class of blur-text will render a burred text effect:

CSS3 Blurred Text

Lovely. Unfortunately, not all browsers support text-shadow. IE9 and below apply the transparent color but do not display the shadow — the text becomes invisible. We needed to rely on JavaScript solutions such Modernizr or our own text-shadow detection code to detect CSS support and react accordingly.

Using JavaScript to detect CSS3 properties is awful. It’ll fail if JavaScript’s disabled and feels dirty. I have to bathe in disinfectant every time I do it. Fortunately, another solution has arrived in native CSS: the @supports rule. The basic syntax:

 @supports <condition> { /* rules */ } 

We’d use the following code for our blurred text:

 @supports (text-shadow: 0 0 5px #000) { .blur-text { color: transparent; text-shadow: 0 0 5px #000; } } 

You can use logical AND, OR and NOT, e.g.

 @supports ( (display: table-cell) and (display: list-item) ) { /* styles */ } 

as well as check for vendor-specific prefixes:

 @supports ( (-webkit-transform: rotate(90deg)) or (-moz-transform: rotate(90deg)) or (-ms-transform: rotate(90deg)) or (-o-transform: rotate(90deg)) or (transform: rotate(90deg)) ) { /* styles */ } 

Older browsers which don’t understand @support will not render the styles — but they’re unlikely to understand the properties you’re attempting to use.

Unfortunately, @supports has fairly limited browser compatibility. At the time of writing, only Opera 12.1 features it as standard. It’s available in Firefox 17 if the layout.css.supports-rule.enable about:config setting is changed to true. It should also be implemented in Chrome 24 but it may be some time before @support arrives in IE and Safari.

That said, @supports is promising and the days of having to use Modernizr-like JavaScript style detection are numbered.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!

Latest Remote Jobs