CSS:after encoding characters in content

CssUnicodeCss SelectorsPseudo ElementCss Content

Css Problem Overview


I am using the following CSS, which seems to be working:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}    

The characters however cannot seem to be encoded like this, as the output is literal and shows the actual string:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}   

If I can't encode it, it feels like I should use something such as .append() in jQuery, as that supports the encoding. Any ideas?

Css Solutions


Solution 1 - Css

To use encoded Unicode characters in content you need to provide either the characters themselves (as you do), or their UTF-8 escape sequences instead of HTML entities:

a.up:after { content: " \2193"; }
a.down:after { content: " \2191"; }   

Solution 2 - Css

Why do you want to encode those characters anyway? Remember, you're writing CSS, not HTML. Your code:

a.up:after{content: " ↓";}
a.down:after{content: " ↑";}

is perfectly valid, as long as you save the file with UTF-8 encoding and send the appropriate header:

Content-Type: text/css; charset=utf-8

Encoding characters is only used in HTML so that there is no ambiguity between content and tags. Thus, you would encode< as &lt; so that the browser doesn't think it's the beginning of a tag. Stuff like &darr; are just commodities for people who don't know how to use utf-8 (or can't, for whatever reason) :).

Solution 3 - Css

Just want to add that if you want to set dynamically the value of content via the attr() function, the above won't work. See

document.getElementById('wontwork').setAttribute('data-sym', ' \2714 ');
document.getElementById('willwork').setAttribute('data-sym', ' \u2714 ');

button::before {
  content: attr(data-sym);
}
* {
  font-size: 30px
}

<button id='wontwork' data-sym='to-be-replaced'>not rendered</button>
<button id='willwork' data-sym='to-be-replaced'>rendered !</button>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontheoriseView Question on Stackoverflow
Solution 1 - CssBoltClockView Answer on Stackoverflow
Solution 2 - CssFelixView Answer on Stackoverflow
Solution 3 - CsskeepAliveView Answer on Stackoverflow