@charset

Term side of the Card.
Topic: Directives
Unit title: @charset
Categories: Directive
Explanation side of the Card

Explanation: The directive that declares the character encoding of a stylesheet, like UTF-8. It should be placed at the very top of the CSS file, ensuring that the browser correctly interprets the characters in the file.

Browser compatibility:
  • The chrome browser supports this feature starting from version 2.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.5.
  • The safari browser supports this feature starting from version 4.
Availability: 

Example

Wrongcss
/* styles */
@charset 'utf-8';
Rightcss
@charset "UTF-8";
/* styles */

@charset must be the first bytes of the file and use double quotes, or browsers skip it.

Common mistakes

  • Placing @charset after a comment or blank line, so it is ignored.
  • Using single quotes, which makes the rule invalid.

Key points

  • @charset is the very first thing in the file, with double quotes and a semicolon.
  • Stylesheets are saved as UTF-8, served with a UTF-8 Content-Type header.

Interview questions

When is @charset needed?

Only when the CSS has non-ASCII characters and the server does not send a charset. A UTF-8 file with a correct header doesn't need it.

Can I use @charset in a <style> tag?

No, it is ignored in inline styles and style attributes; the HTML document encoding applies.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy