CSS @charset At-Rule

The CSS @charset at-rule can be used to declare the character encoding used in the style sheet.

Here's an example of using the @charset at-rule:

When using the CSS @charset at-rule, it must be the first line in the document, and it must not be preceded by any other character — not even a space.

This example sets the character encoding of the style sheet to UTF-8. You should always use UTF-8 as the character encoding for your style sheets and HTML documents unless you have a reason not to. UTF-8 is the preferred character encoding of CSS and HTML5. In fact, the WHATWG's Encoding specification states:

Authors must use the UTF-8 encoding and must use the ASCII case-insensitive "utf-8" label to identify it.

If you really must use another character encoding, these character encodings (from the WHATWG's Encoding specification) have been tested against browser implementations. Use the values in the left column of that table.

You can also use the IANA registry, however this list hasn't necessarily been tested against browsers.

Other Methods of Declaring the Character Encoding

The CSS @charset at-rule is an optional declaration that doesn't need to be used in most cases. This is because the character encoding can be (and usually is) set via another method (see below). However, it can be included as part of a best-practice approach to ensure that the correct character encoding is being declared. It can also be useful when using non-ASCII characters with some CSS properties (for example, with the content property).

Here's the order in which the browser will try to determine the character encoding of a style sheet:

  1. Byte order mark (BOM). The browser will use the value of the Unicode byte-order character placed at the beginning of the file. If a valid value is found, the browser will use that encoding.
  2. HTTP Headers. If the character encoding can't be determined by the BOM method, the browser will look for the charset attribute of the Content-Type: HTTP header (or the equivalent in the protocol used to serve the style sheet).
  3. The @charset at-rule. If it still can't determine the character encoding, it will use the value of the CSS @charset at-rule (if present and valid).
  4. The referring document. If the browser still can't determine the character encoding, it will check the referring document and use its character encoding (if found).
  5. Use UTF-8. If after all of the above checks the browser still can't determine the character encoding, it will assume it to be UTF-8.

Official Specifications

The @charset at-rule is defined in Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification (W3C Recommendation 07 June 2011).