External CSS Files and Media Types
60

External CSS Files and Media Types

I think I might have found a bug in W3C’s CSS validator.

There are two ways to import an external style sheet: either by using the <link> tag and a href attribute, or by using the @import rule in the CSS file. The latter has some advantages because certain older browsers can not parse that specific rule, depending on how you write it.

If you want a certain external style sheet to target a specific medium (or media), there are a couple of ways of doing that. If you are using <link>, just add a media attribute and specify the media type. But if you are using the @import rule, you can specify media in two ways: either by adding a media attribute to your <style> tag, or you can specify media types after the url property. Here are three basic examples:

  1. <link href="styles.css" media="screen" rel="stylesheet" type="text/css">
  2. <style type="text/css" media="screen">@import 'styles.css';</style>
  3. <style type="text/css">@import 'styles.css' screen;</style>

All three ways works in most browsers. There are some differences in compability for older browsers, but that’s another topic. So what if you want to address several media types at once? You can comma separate more than one media for each style sheet, like so:

  1. <style type="text/css">
  2. @import 'styles.css' screen, projection;
  3. </style>

Nice. So what about this:

  1. <style type="text/css" media="screen, projection">
  2. @import 'styles.css';
  3. </style>

No. It works, but will through you a validation error using the CSS validator at W3C. I have seen this usage on a lot of sites, but it is actually invalid. Or is it? I have added it in my own header here in the kitchen, so you can see for yourself. I have spent nearly 2 hours looking for an explanation to why, but I couldn’t find any answers. Does anyone else know?

As far as I can see, there can not be a logical explanation to why more than one media type is allowed for the media atrribute in the <link> tag, but not in the <style> tag. Is it merely a bug in the CSS validator?