I've been seeing this instruction as the very first line of numerous CSS files that have been turned over to me:
@charset "UTF-8";
What does it do, and is this at-rule necessary?
Also, if I include this meta tag in my "head" element, would that eliminate the need to have it also present within my CSS files?
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
The @charset CSS at-rule specifies the character encoding used in the style sheet. It must be the first element in the style sheet and not be preceded by any character; as it is not a nested statement, it cannot be used inside conditional group at-rules.
Why use UTF-8? An HTML page can only be in one encoding. You cannot encode different parts of a document in different encodings. A Unicode-based encoding such as UTF-8 can support many languages and can accommodate pages and forms in any mixture of those languages.
UTF-8 is the most widely used way to represent Unicode text in web pages, and you should always use UTF-8 when creating your web pages and databases. But, in principle, UTF-8 is only one of the possible ways of encoding Unicode characters.
Quick answer. You should always use UTF-8 as the character encoding of your style sheets and your HTML pages, and declare that encoding in your HTML. If you do that, there is no need to declare the encoding of your style sheet.
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 ↗ 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:
@charset
rule.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.
@charset
if more than one name is registered for the same encoding.@charset
. There is a support table. I do not trust this. :)It tells the browser to read the css file as UTF-8. This is handy if your CSS contains unicode characters and not only ASCII.
Using it in the meta tag is fine, but only for pages that include that meta tag.
Read about the rules for character set resolution of CSS files at the w3c spec for CSS 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With