css 2.1 tricks
by Waylan Limberg
While I understand why each occurrence of the the ID attribute must be unique in HTML, sometimes I find it annoying. Sure, I can always include a class, or two, but that seems redundant at times. Besides, isn't that not quite a complete separation of presentation from content?
Let me demonstrate: Consider the source of this page. Every weblog entry is assigned the attribute class='entry'. I'm using a class because I want all entries to be styled the same. However, what if I wanted one of the entries to be styled differently? Or what if I wanted to link farther down the page (using # in the url)? Then, I need a unique ID. So I add id='post-#' where # is the post number pulled from the database by my cms. If only there was a way to specify all IDs that include 'post' in the value in the CSS.
Turns out there is! As I was reviewing the CSS 2.1 Specification I can upon something I have never seen used before. Under Section 5.8.1 I learned that we can refer to an attribute like this: [att|=val]. The Specification explains:
Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value.
The following example is provided for demonstration:
The following rule will match for values of the "lang" attribute that begin with "en", including "en", "en-US", and "en-cockney":
*[lang|="en"] { color : red }
Yes, I realize that “This is primarily intended to allow language subcode matches”. But, “primarly” is not 'always', now is it?
Therefore I could conceivably drop the class from my weblog entries and refer to all entries in my CSS like this:
*[id|="post"]
If I ever desired to single out a single entry I would simply refer to that entries' ID in the conventional manner.
Now, that is what I call separation of presentation from content! Oh yeah, and it makes the file smaller resulting in speeder downloads, which is, after all, a common argument in favor of said separation.
The question is: Does it work? It does in Mozilla/Firebird/Firefox. I'm not so sure about other browsers. I have a sneaking suspicion that's why I have never seen it used before. Too bad.