Sub topic 3
Declaring UTF-8 with meta charset
This chapter assumes you can write basic HTML (elements, attributes, nesting) and know the parts of a document: doctype, html, head, and body. It also assumes you know that a browser turns the bytes it downloads into a page. By the end, you will be able to declare the encoding correctly, place it where the browser will find it, and diagnose garbled text.
Why encoding matters
A file on disk or a response on the network is a sequence of bytes. A character encoding is the rule that maps those bytes to characters. The same bytes produce different text under different encodings, so the browser must know which rule to apply before it can show the page.
The letter é is stored in UTF-8 as two bytes, C3 A9. If a browser reads those two bytes as windows-1252, an older single-byte encoding, it shows é instead. Garbled text like this is called mojibake. The following Python script reproduces it:
text = "café"
data = text.encode("utf-8")
print(data) # b'caf\xc3\xa9'
print(data.decode("utf-8")) # café
print(data.decode("windows-1252")) # caféThe bytes never change. Only the rule used to read them changes. The meta charset declaration tells the browser which rule to use.
The declaration
<meta charset="utf-8">This is a meta element with a charset attribute. It has no content attribute and no closing tag. Three details are worth knowing:
- The value is not case sensitive.
UTF-8,utf-8, andUtf-8all work. Lowercaseutf-8is the common style. - UTF-8 is the encoding to use for any new document. The HTML Standard requires authors to use it. The standard also lists legacy encodings that authors should not use for new content.
- The declaration must appear within the first 1024 bytes of the document, and it must be fully contained in those bytes.
UTF-8 can represent every Unicode character. Because of that, one file can contain English, Arabic, Japanese, and emoji without special handling.
The older http-equiv form
You may see this longer form in older code:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">It is valid and has the same effect, but it is longer and easier to get wrong. Use <meta charset="utf-8"> in new pages. A document can contain only one encoding declaration of either kind. Do not mix the two forms.
How the browser decides the encoding
The meta tag is not the only source of encoding information. The browser checks several sources in a fixed order and uses the first one that gives an answer.
| Priority | Source | Notes |
|---|---|---|
| 1 | Byte order mark (BOM) at the start of the file | A UTF-8 BOM is the bytes `EF BB BF`. It overrides everything else. |
| 2 | `charset` parameter of the HTTP `Content-Type` header | For example `text/html; charset=utf-8`. It overrides the `meta` tag. |
| 3 | `meta charset` found by scanning the first 1024 bytes | This is the source you control from the HTML file alone. |
| 4 | Heuristics or a locale default | Often windows-1252 for Western locales. This is a guess. |
The diagram shows the same order as a decision flow.
This order has a practical consequence. If your server sends Content-Type: text/html; charset=iso-8859-1, a correct <meta charset="utf-8"> in the file is ignored. The page shows mojibake even though the HTML is right. The fix is on the server: send charset=utf-8 or remove the charset parameter. Keeping the header and the meta tag consistent avoids this class of bug.
Placement: first in the head, within 1024 bytes
The browser cannot wait until it has read the whole file to choose an encoding. It starts decoding almost immediately, so it runs a quick prescan of the first 1024 bytes looking for a meta declaration. If the declaration is not in that window, the prescan finds nothing and the browser falls to its guess. Some browsers then notice the meta tag later and restart parsing with the new encoding. That restart wastes time and can cause a visible flash or re-layout. Other content, such as scripts that already ran, may also be affected.
The rule that follows is simple: make meta charset the first element inside head.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Trail Running Shoes - Example Store</title>
<meta name="description" content="Compare lightweight trail running shoes by grip, cushioning, and weight.">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Trail Running Shoes</h1>
</body>
</html>Here the declaration begins about 70 bytes into the file. The risk appears when content comes before it. Anything that counts toward the 1024 bytes pushes the declaration later, including these:
- A long
titleor a long block of comments above the declaration. - Inline scripts or inline styles placed before it.
- Many
linktags for preloading, placed before it. - Template-engine output or generated comments inserted at the top.
- Wide indentation or blank lines, which are bytes too.
Note that the 1024 bytes are counted as bytes, not characters. If a long non-ASCII title appears before the declaration, each character may take two to four bytes, so the window fills faster than you expect.
The file must really be UTF-8
The declaration is a claim about the bytes. It does not convert them. If your editor saves the file as windows-1252 but the file says utf-8, the browser follows the claim and misreads any non-ASCII bytes. Plain ASCII text looks fine under both encodings, so the bug often stays hidden until someone adds an accented letter, a curly quote, or an emoji.
To avoid this, check three places:
- Save the source file as UTF-8. Most modern editors do this by default, and the setting is usually shown in the status bar.
- Send
Content-Type: text/html; charset=utf-8from the server, or send nocharsetparameter. - Keep
<meta charset="utf-8">first in the head, so the file still works when opened from disk or served by a tool that sends no encoding.
A UTF-8 BOM is allowed and takes priority, but it is not needed. It can cause trouble in some tools, such as stray characters at the start of concatenated output. Saving as "UTF-8 without BOM" is the usual choice.
What the declaration does not do
- It does not apply to external resources. A CSS file or JavaScript file has its own encoding rules. For these files, the server's
Content-Typeheader matters most, and a CSS file can use an@charsetrule. Serve all of them as UTF-8 to match. - It is ignored in XHTML documents served as XML. XML parsers use the XML declaration and the HTTP header instead.
- It does not replace escaping. Characters such as
<and&still need<and&in text content. - Character references like
éstill work under any encoding. They are a fallback for characters you cannot type, but they are not a substitute for declaring UTF-8.
Diagnosing mojibake
When text looks wrong, work through the sources in priority order.
- Look at the symptom.
éin place ofé, or’in place of a curly apostrophe, means UTF-8 bytes were read as windows-1252. A diamond with a question mark (�) means the decoder met bytes that are invalid in the encoding it used. This often means a non-UTF-8 file was read as UTF-8. - Check the HTTP header. In a terminal,
curl -sI https://example.com/page.htmlprints the response headers. Look at theContent-Typeline for acharsetvalue that disagrees with the file. - Check the file. Inspect its bytes with a tool such as
file -i page.html, which reports the detected encoding, or reopen it in an editor with the encoding set to UTF-8. - Check the placement of
meta charsetand make sure it is the first element inhead, with nothing large above it. - Check the build pipeline. Templates, databases, and generators that handle text may re-encode it, so the problem can appear after your HTML file was correct.
Browser developer tools also help. In the Network panel, select the document request and read its response headers. In the Elements panel, confirm that the meta element sits at the top of head. Later chapters in this tutorial cover verification in more depth.
Summary of rules
- Use
<meta charset="utf-8">in every document. - Place it first in
head, and keep it within the first 1024 bytes. - Save the file as UTF-8, and serve it with
charset=utf-8or no charset parameter. - Remember that the BOM and the HTTP header both outrank the
metatag. - Prefer the short form over the
http-equivform.
Exercise
A page contains <meta charset="utf-8"> as the first element in its head, and the file is saved as UTF-8. The server sends Content-Type: text/html; charset=iso-8859-1. The browser shows é where the text should read é. Explain why, and name two ways to fix it.
Show answer
The HTTP Content-Type charset has higher priority than the meta tag, so the browser decodes the UTF-8 bytes as ISO-8859-1 and shows each byte as a separate character. The meta tag is ignored. Fix it by changing the server to send charset=utf-8, or by removing the charset parameter from the header so the meta tag is used.
Exercise
A developer puts a 1,200-byte HTML comment containing a license notice at the top of head, followed by <meta charset="utf-8">. The page works on the developer's machine but shows broken text on some browsers when the server sends no charset. What is the problem, and how do you fix it?
Show answer
The comment pushes the declaration past the first 1024 bytes, so the browser's prescan never sees it and falls back to a guessed encoding. Move <meta charset="utf-8"> to be the first element in head, above the comment, or shorten the comment.