CSS - @charset



The @charset at-rule in CSS is used to specify the character encoding of an external style sheet.

It is important to note that in many cases, you don't need to explicitly use the @charset rule, as most modern web servers and text editors save CSS files with UTF-8 encoding by default. However, in some specific situations, when dealing with non-standard character encodings or if you want to be explicit about the encoding, the @charset rule can be useful.

Overview

  • The @charset must be the first element in your style sheet.

  • It should not be preceeded by any character.

  • It is not a nested statement and thus should not be used in a conditional group at-rules.

  • In case multiple @charset at-rules are specified, only the first one will be applied or used.

  • The @charset at-rule can not be used inside a style attribute of an HTML element or inside the <style> tag.

  • It is useful when using the non-ASCII characters in some of the CSS properties, such as content.

There are various ways to define the character encoding of a style sheet, but the browser will follow these methods in the given order:

  • The Unicode byte-order character's value will be placed at the start of the file.

  • The value provided by the charset attribute in the Content-Type: HTTP header or its equivalent in the protocol used to deliver the style sheet.

  • The charset CSS at-rule.

  • The character encoding specified by the referring document, i.e., the charset attribute of the <link>, should be used. Note: Though this method is obsolete, it should be avoided.

Syntax

@charset "";
/* Example: @charset    
@charset "UTF-8";
@charset "iso-8859-15";

Possible Value

The only value that @charset at-rule can have is charset.

  • It is a <string> that denotes the character encoding which can be used.

  • It should list the name of a web safe character encoding, as per the IANA-registry.

  • It must be defined in double-quotes, following one space character (U+0020), and at last terminated by a semicolon (;).

  • In case multiple names are associated with an encoding, the one marked with preferred value, must be considered.

Valid and Invalid @charset declarations

The syntax shown below is the correct way of declaring the @charset at-rule.

@charset "UTF-8";

The syntax shown below is the incorrect way of declaring the @charset at-rule.

@charset 'UTF-8'; /* Single quotes is invalid */
@charset   "UTF-8"; /* More than two spaces after @charset */
 @charset "UTF-8"; /* space before @charset */
@charset "UTF-8" /* Not terminated with a semi-colon */
@charset UTF-8; /* Invalid, as the UTF-8 is a string and requires double quotes */
Advertisements