This is useful in contexts where the encoding is not told per HTTP header or other meta data, e.g. the local file system.
Imagine the following stylesheet:
[rel="external"]::after
{
content: ' ↗';
}
If a reader saves the file to a hard drive and you omit the @charset
rule, most browsers will read it in the OS’ locale encoding, e.g. Windows-1252, and insert a?— instead of an arrow.
Unfortunately, you cannot rely on this mechanism as the support is rather … rare.
And remember that on the net an HTTP header will always override the @charset
rule.
The correct rules to determine the character set of a stylesheet are in order of priority:
- HTTP Charset header.
- Byte Order Mark.
- The first
@charset
rule.
- UTF-8.
The last rule is the weakest, it will fail in some browsers.
The charset
attribute in <link rel='stylesheet' charset='utf-8'>
is obsolete in HTML 5.
Watch out for conflict between the different declarations. They are not easy to debug.
Recommended reading
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…