CSS Conditional Rules: Exciting and Scary

This month the W3C came out with a brand new working draft for CSS Conditional Rules (W3C Draft).

Conditional rules are basically @-rules that apply CSS only when certain conditions are met. The most powerful is the @supports condition. You might be able to guess how it works by looking at the example below.

#nav {
background-color: #aaa;
color: #fff;
@supports ( text-shadow: -1px -1px 0 #000 ) {
#nav {
text-shadow: -1px -1px 0 #000;
color: #ccc;

The CSS above would set the nav background color to #aaa and font color to #fff. And then, if the browser supports text-shadow, instead use a font color of #ccc with a black text shadow. The use case would be that the text shadow provides some extra contrast; if text shadow is not available, use a font color with greater contrast–in this case white on light gray.

Older browsers that do not recognize @supports or do not support text-shadow will ignore the @supports section. It becomes a great way to degrade gracefully without having to maintain and update browser-specific stylesheets. Gone would be the days of including files like ie.css.

The other @-rule in the specification is@document. It allows you to specify CSS rules that should only be applied to a certain set of URLs. Take the following examples:

/* Apply styles to a domain */
@document domain("w3.org") {/*...*/}

/* Apply styles to a URL */
@document url("http://www.w3.org/Style/CSS/") {/*...*/}

/* Apply styles to URLs that begin with something */
@document url-prefix("http://www.w3.org/Style/CSS/") {/*...*/}

/* Apply styles to URLs that match a regular expression */
@document regexp("http://www.w3.org/TR/\\d{4}/[^/]*-CSS2-\\d{8}/") {/*...*/}

The idea is very interesting. But in most cases it is very bad in practice. We don’t want styling to rely on our URL scheme or MVC routes. That functionality should be logically separate. But I can see it being useful in a small number of cases where you can’t control the HTML.

Apparently this idea is not new at all. In 2004, Firefox began supporting @-moz-document which is great for user-defined spreadsheets (mailing list post here). For example, I can give reddit.com a whole new look by adding a section to my browser default stylesheet. I did in fact get such CSS from userstyles.org.

I am excited about @supports. I see it helping accelerate adoption of new CSS features and helping futureproof against browser updates. I have mixed feelings about @document because it can be so easily abused. Abused in that a site ends up with a spaghetti code of CSS that is tightly coupled with back-end code.