The CSS @charset at-rule
The CSS @charset at-rule declares the character encoding of a stylesheet, e.g. @charset "UTF-8";. It must be the very first thing in the file — no comments or whitespace before it — and written exactly, with double quotes. In practice UTF-8 is almost always right, and a server header or the page encoding usually makes it unnecessary.
Overview
@charset tells the browser which character encoding a stylesheet uses. It only matters when the CSS file itself contains non-ASCII characters — a content: "★" value, say, or non-English text in a generated string — where the wrong encoding would garble them.
It comes with strict rules: it must be the very first thing in the file, with absolutely nothing before it — not a space, not a comment — and it has to be written exactly as @charset "UTF-8"; with double quotes. If anything precedes it, the browser ignores it.
In modern practice you rarely need it. The encoding is more reliably set by the HTTP Content-Type header your server sends, or inherited from the HTML document's own charset, both of which take precedence over @charset. And the answer is essentially always UTF-8, which covers every character you are likely to use. Include it as a belt-and-braces measure if your CSS has non-ASCII content and you cannot rely on the server header.
Syntax
@charset "UTF-8";
/* must be the first bytes of the file — nothing before it */
Best practices
- If you use it, place it as the very first bytes of the file — any character before it makes it invalid.
- Always use UTF-8; it covers virtually every character you will need.
- Prefer setting the encoding via the server's
Content-Typeheader, which is more reliable and overrides@charset. - You only really need it when the stylesheet contains non-ASCII characters and the encoding is not set elsewhere.
Frequently asked questions
What does @charset do in CSS?
@charset "UTF-8";, so non-ASCII characters in the file are read correctly.