Character Entities in CSS

All sorts of symbols are commonly embedded within documents, such as © copyright symbols and funny angled » brackets to name just a few. In the world of HTML we can represent these with character entity references[1] which are little codes such as © (which, when rendered by a browser, are magically transformed into the corresponding symbol – in this case a copyright symbol).

What About in CSS?

I was recently working on a stylesheet and had a good case for implementing generated content using the CSS content property[2]. That’s not actually important; what is important is that I wanted to use a character entity reference inside my stylesheet.

Working on what I thought was the reasonable assumption that it would work in a manner similar to HTML, I cracked on and did something like this:

/**
 * Preceed each bullet point in this section
 * with some natty little arrow symbols.
 */
ul.recent-news li:before {
        content: "»";
}

Did that work as expected? No, it did not – as it turns out CSS doesn’t use the same notation[3]. What I actually needed was this:

/**
 * Preceed each bullet point in this section
 * with some natty little arrow symbols.
 *
 * Right angle quotes, "»", is equivalent 
 * to U+00BB, which can be expressed as \BB in
 * CSS.
 */
ul.recent-news li:before {
        content: "\BB";
}

 

Footnotes
  1. More about character entity references can be found in this W3C Recommendation.
  2. The :before selector can be used in CSS to insert a chunk of text before every matching element, there is also a corresponding  :after selector. So if I wanted every paragraph to be terminated with a piece of text like “This is the end of the paragraph” then, rather than actually type that out at the end of every paragraph, I could use some CSS magic to do the hard-work for me.
  3. W3C summarizes escape sequences in CSS in this document.

Speak Your Mind

*