HTML & CSS
Article
By Craig Buckler

How to Use Character Entities in HTML, CSS and JavaScript

By Craig Buckler
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

You’ve almost certainly encountered entities in HTML pages. They’re commonly used for international characters, mathematical operators, shapes, arrows and other symbols. For example:


♠
♣
♥
♦
©
®

These map directly to UTF-8 characters. The symbol for PI (π) can either be written as π or its UTF-8 number π. You can look-up popular symbols on the HTML Character Entity Reference to discover their HTML entity code and UTF-8 index number.

Strictly speaking, it’s not necessary to use these codes if you’re serving pages as UTF-8; the default character set for HTML and XML documents. However, there may be occasions when you’re not using UTF-8, adjacent characters are causing issues, or it’s difficult to enter a specific symbol on your keyboard. Similarly, you may be using ANSI or another encoding method for CSS and JavaScript files.

--ADVERTISEMENT--

Entities in CSS

Adding content via pseudo elements is increasingly common — especially if you’re using webfont icons. To add any UTF-8 character, you need to find its number and convert that to hexadecimal. For Pi, it’s 03C0. This can be added within a CSS file using a preceding backslash, e.g.


#pi:before
{
	content: "\03C0";
}

Entities in JavaScript

Like CSS, JavaScript requires the UTF-8 number in hexadecimal. In this case, however, it must be escaped using a preceding “u”, e.g.


var pi = "u03C0";

If the character code is 255 or less, you can also use standard JavaScript 2-digit hexadecimal notation, e.g.


var copyright = "xA9";

That’s all there is to it. Simple solutions, but ones I always forget!

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?