CSS Reference ยท At-rules
The @charset at-rule
Reference for the CSS @charset at-rule: how it declares a stylesheet's character encoding, the strict rules for using it, and when you can skip it.
The @charset at-rule tells the browser which character encoding an external stylesheet uses, so non-ASCII characters (accents, symbols, quotes in content) are decoded correctly. The only practical value today is "UTF-8".
It is unusual among at-rules: it must be the very first thing in the file, with no whitespace or comments before it, and it must be written exactly as shown, in double quotes. Anything else makes the browser ignore it.
@charset "UTF-8"; .quote::before { content: "โ"; }
Try it
@charset has no effect inside a <style> element (the page encoding already applies), so this demo shows the safe alternative: CSS escapes that avoid any encoding problem.
Syntax
@charset "<encoding-name>";
- Exact form:
@charset "UTF-8";with a space after@charset, double quotes and a semicolon. - Position: the first characters of the file. Not allowed inside
<style>elements or instyleattributes (it is ignored). - Not a rule you can nest or repeat. Only one, at the top.
Values
| Syntax and arguments | Description |
|---|---|
"UTF-8" |
The standard, recommended encoding. |
Other names ("ISO-8859-1") |
Legal, but legacy; avoid in new work. |
Usage notes
- How the browser picks the encoding. In order: the HTTP
Content-Typeheader's charset, a byte-order mark, the@charsetrule, the encoding of the page that linked the sheet, and finally UTF-8. SettingContent-Type: text/css; charset=utf-8on the server makes@charsetunnecessary. - Save files as UTF-8. The declaration only helps if the file really is in that encoding.
- Use escapes for portability.
content: "\2713"works whatever the encoding, and is common in icon-style rules. - Bundlers. Concatenating sheets can leave an
@charsetin the middle of a file, where it is ignored; build tools usually keep one at the top or drop it. - Does not affect the HTML. The page needs its own
<meta charset="utf-8">. @importafter it.@importrules may follow@charset, since@charsetis not a real rule.
Browser support
Supported in every browser. Most modern sites omit it because servers send the charset in the header.
Related
@import@font-face- Lesson: Adding CSS
- Lesson: Syntax