HTML character encoding: charset
Character encoding tells a browser how to turn stored bytes into readable text. UTF-8 is the usual choice for modern HTML.
What you will learn
- What character encoding does and why mismatches cause mojibake
- How to declare UTF-8 with
meta charset="utf-8" - Why the HTML, server, and saved file encodings must agree
Declare UTF-8
<head>
<meta charset="utf-8">
<title>My page</title>
</head>
Put the declaration near the beginning of the <head>, before the document contains much text. The browser can then decode characters such as accented letters, emoji, and Japanese correctly.
Encoding must agree
- Save the HTML file as UTF-8.
- Declare UTF-8 in the HTML.
- Send a matching HTTP
Content-Typeheader from the server.
If these layers disagree, the browser may decode the same bytes with the wrong character set and display unreadable symbols. Fix the source or server configuration rather than adding replacement characters to the text.
Do not confuse language and encoding
The lang attribute describes the language of the content, while charset describes how characters are encoded. A page can be written in Japanese, English, or several languages while using UTF-8.
Common mistakes
- Saving a file in a legacy encoding while declaring UTF-8.
- Putting the charset declaration so late that the browser has already decoded text incorrectly.
- Changing the HTML declaration but leaving the HTTP response header inconsistent.
- Using
langas if it selected the character encoding.