- Атрибут charset
- Поддержка браузерами
- Спецификация
- Значения
- Атрибут charset
- Синтаксис
- Значения
- Значение по умолчанию
- Типы тегов
- @charset
- Syntax
- Formal syntax
- Examples
- Valid and invalid charset declarations
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Declaring character encodings in CSS
- Question
- Quick answer
- Details
- Using @charset
- What about the byte-order mark?
- Using HTTP
- Additional information
- Working with non-UTF-8 encodings
- The charset attribute on the link element
- Further reading
- @charset
- Синтаксис
- Значения
- Браузеры
- CSS по категориям
- Селекторы
Атрибут charset
Атрибут / параметр charset (от англ. «charset» ‒ «кодировка») указывает кодировку внешнего присоединяемого ресурса.
Поддержка браузерами
Спецификация
Верс. | Раздел |
---|---|
HTML | |
2.0 | |
3.2 | |
4.01 | 12.2 The A element charset = charset [CI]. DTD: Transitional Strict Frameset |
5.0 | |
5.1 | |
XHTML | |
1.0 | Extensible HyperText Markup Language DTD: Transitional Strict Frameset |
1.1 | Extensible HyperText Markup Language |
Значения
В качестве значения указывается кодировка внешнего ресурса. Примеры кодировок:
ISO-8859-1 Кодировка используемая большинством западноевропейских языков. (Данная кодировка также известна как «Latin-1».) ISO-8859-5 Кодировка поддерживающая кириллицу. SHIFT_JIS EUC-JP Японская кодировка UTF-8 Одна из общепринятых и стандартизированных кодировок текста, поддерживающая множество различных письменностей. windows-1251 Кодировка с поддержкой кириллицы.
Регистр символов: не учитывается.
Атрибут charset
Указывает кодировку документа на который ссылается тег .
Синтаксис
Значения
Название кодировки, например UTF-8.
Значение по умолчанию
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Типы тегов
HTML5
Блочные элементы
Строчные элементы
Универсальные элементы
Нестандартные теги
Осуждаемые теги
Видео
Документ
Звук
Изображения
Объекты
Скрипты
Списки
Ссылки
Таблицы
Текст
Форматирование
Формы
Фреймы
@charset
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. If several @charset at-rules are defined, only the first one is used, and it cannot be used inside a style attribute on an HTML element or inside the element where the character set of the HTML page is relevant.
This at-rule is useful when using non-ASCII characters in some CSS properties, like content .
As there are several ways to define the character encoding of a style sheet, the browser will try the following methods in the following order (and stop as soon as one yields a result) :
- The value of the Unicode byte-order character placed at the beginning of the file.
- The value given by the charset attribute of the Content-Type: HTTP header or the equivalent in the protocol used to serve the style sheet.
- The @charset CSS at-rule.
- Use the character encoding defined by the referring document: the charset attribute of the element. This method is obsolete and should not be used.
- Assume that the document is UTF-8
Syntax
@charset "UTF-8"; @charset "iso-8859-15";
Formal syntax
A denoting the character encoding to be used. It must be the name of a web-safe character encoding defined in the IANA-registry, and must be double-quoted, following exactly one space character (U+0020), and immediately terminated with a semicolon. If several names are associated with an encoding, only the one marked with preferred must be used.
Examples
Valid and invalid charset declarations
@charset "UTF-8"; /* Set the encoding of the style sheet to Unicode UTF-8 */ @charset 'iso-8859-15'; /* Invalid, wrong quoting style used */ @charset "UTF-8"; /* Invalid, more than one space */ @charset "UTF-8"; /* Invalid, there is a character (a space) before the at-rule */ @charset UTF-8; /* Invalid, without ' or ", the charset is not a CSS */
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 1, 2023 by MDN contributors.
Your blueprint for a better internet.
Declaring character encodings in CSS
Intended audience: CSS coders, Web project managers, and anyone who wants to know how to declare the character encoding of a CSS file.
Question
How do I declare the character encoding of a CSS style sheet?
If you have any non-ASCII text in your CSS file, for example non-ASCII characters in font names, in values of the content property, in selectors, etc., you need to be sure that the CSS parser knows how to transform the bytes into characters correctly, so that it understands your CSS code. This article describes how to do this.
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.
Other approaches are only needed if your style sheet contains non-ASCII characters and, for some reason, you can’t rely on the encoding of the HTML and the associated style sheet to be the same. In this case you should use @charset or HTTP headers to declare the encoding. (If your HTML and CSS files use the same encoding, the latest versions of major browsers will apply the encoding of the HTML file to the CSS stylesheet.)
Details
Using @charset
As mentioned above, you should only use this when the style sheet and the calling HTML file are in different encodings.
It is important to understand that, although the @charset declaration looks like a CSS at-rule, it is not parsed as such for detection of the character encoding. Only an exact byte sequence, beginning with the very first byte in the style sheet, will be effective. Variations, even those that would be valid for a normal at-rule with the same syntax, are silently ignored.
To set the character encoding inside the style sheet, use the following sequence of bytes, apart from the charset-name , at the very start of the file, one byte per character.
The charset-name is case-insensitive, but should always be utf-8 for new style sheets. If you really cannot use UTF-8 for your style sheet, see Working with non-UTF-8 encodings, below.
Only one @charset byte sequence may appear in an external style sheet and it must appear at the very start of the document. It must not be preceded by any characters, not even comments.
Note! It is not enough to simply put @charset «utf-8»; at the top of the style sheet – you need to also save your style sheet in the UTF-8 character encoding. (See Applying an encoding to your content.)
Important: Since the HTTP header has a higher precedence than the in-document @charset declaration, you should always take into account whether the character encoding is already declared in the HTTP header. If it is, @charset must be set to declare the same encoding, and will only have an effect when the style sheet is read in a context where there are no HTTP headers (eg. from a local drive).
The techniques index provides a set of links to help you detect whether a declaration is being sent in the HTTP header.
What about the byte-order mark?
The CSS3 Syntax specification says that if you have a UTF-8 byte-order mark at the start of your file, this should cause the browser to read the style sheet as UTF-8, regardless of any other declaration. Unfortunately, at the time of writing this is not supported interoperably – Internet Explorer 10 and 11 still give higher precedence to the HTTP header and @charset declarations.
So for the time being you should rely on the @charset or HTTP header declarations instead. The former has the additional advantage that it helps people looking at the source code to ascertain what is the encoding of the style sheet. The byte-order mark is invisible.
Using HTTP
The server may already send a default character encoding declaration in the HTTP Content-Type header when your browser retrieves a style sheet, or it may not. This line in the HTTP response would indicate that the file is encoded in UTF-8.
Content-Type: text/css; charset=utf-8
The techniques index provides a set of links to help you detect whether a declaration is being sent in the HTTP header. For more information about how to set the encoding in HTTP see Setting the HTTP charset parameter .
It could be that the server is serving a style sheet with an encoding declaration that you don’t want, due to server-wide defaults or specific settings, or serving without an encoding declaration when you want one. You can change the situation either for the server as a whole, or for a specific file or set of files, by changing the server settings (globally or locally) or by using code in scripts such as PHP.
The declaration in the HTTP header will always override the in-document declaration, if there is a conflict, except for those browsers where the byte-order mark overrides it.
However, we recommend that if you need to use an HTTP declaration to set the correct encoding, you also include an @charset declaration inside the style sheet. This will ensure that the encoding is still known if the style sheet is used locally or moved, eg. for testing or editing.
Additional information
Most people will not need to know the information in this section. It is provided for the sake of completeness.
Working with non-UTF-8 encodings
This section is only to be read if you really cannot save your style sheet as UTF-8.
Note that although the names appearing in documents referred to here are normally called names, in reality they refer to the encodings, not the character sets. For example, the Unicode character set or ‘repertoire’ can be encoded in three different encoding schemes.
Until recently the IANA registry was the place to find names for encodings. The IANA registry commonly includes multiple names for the same encoding. In this case you should use the name designated as ‘preferred’.
The new Encoding specification now provides a list that has been tested against actual browser implementations. You can find the list in the table in the section called Encodings. It is best to use the names in the left column of that table.
Note, however, that the presence of a name in either of these sources doesn’t necessarily mean that it is OK to use that encoding. Several of the encodings are problematic. If you really can’t use UTF-8, you should carefully consider the advice in the article Choosing & applying a character encoding .
The charset attribute on the link element
The HTML 4.01 specification describes a charset attribute that can be added to the link element to indicate the encoding of the document you are linking to. However, the use of this attribute on a link element is currently obsoleted by the HTML5 specification, so you shouldn’t use it.
Further reading
- Getting started? Introducing Character Sets and Encodings
- Tutorial, Handling character encodings in HTML and CSS
- Related links, Authoring HTML & CSS
- Characters
- Declaring the character encoding in a CSS style sheet
- Characters
@charset
Команда @charset применяется для задания кодировки внешнего CSS-файла. Это имеет значение в том случае, если в CSS-файле используются символы национального алфавита.
Для внешней таблицы стилей браузер последовательно просматривает следующие пункты для определения кодировки таблицы стилей:
- кодировка, которую отдает сервер;
- правило @charset ;
- атрибут charset тега ;
- кодировка, установленная в документе через метатег ( ).
Приведенный список имеет четко выраженную иерархию — чем выше находится пункт, тем выше его приоритет. Если ни один из пунктов не найден, будет установлена кодировка UTF-8.
Синтаксис
Значения
Для русского языка обычно указывается кодировка windows-1251 или utf-8. Значение кодировки обязательно должно быть взято в кавычки.
@charset "windows-1251"; body < font: 11pt Arial, Helvetica, sans-serif; margin: 0; color: #000; >p.new:after
Браузеры
В браузере Internet Explorer до версии 7.0 включительно название кодировки допускается писать без кавычек, что противоречит спецификации CSS.
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
CSS по категориям
Поля
Анимация
Градиент
Скруглённые уголки
Изображения
Псевдоэлементы
Псевдоклассы
Печать
Контент
Интерфейс
Таблица
Отступы
Список
Текст
Шрифт
Форматирование
Размеры
Позиционирование
Границы
Цвет и фон
Селекторы
- Селекторы тегов
- Идентификаторы
- Классы
- Мультиклассы
- Универсальный селектор
- Вложенные селекторы
- Дочерние селекторы
- Соседние селекторы
- Родственные селекторы
- Селекторы атрибутов
- [атрибут=»значение»]
- [атрибут^=»значение»]
- [атрибут$=»значение»]
- [атрибут*=»значение»]
- [атрибут~=»значение»]
- [атрибут|=»значение»]