Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Описание

С помощью функции CSS attr() можно извлекать значение атрибута выбранного элемента и использовать это значение в таблице стилей. Функция работает и с псевдо-элементами. В этом случае возвращается значение атрибута элемента, для которого формируется псевдо-элемент.

Функцию attr() можно использовать с любым свойством CSS, но поддержка иных свойств, кроме content, является экспериментальной.

Синтаксис

/* Пример простого использования */
attr(data-count);
attr(title);

/* С типом */
attr(src url);
attr(data-count number);
attr(data-width px);

/* с фоллбэком */
attr(data-count number, 0);
attr(src url, '');
attr(data-width px, inherit);
attr(data-something, 'default');

Значения

attribute-name
Название атрибута элемента HTML, на который ссылаемся в CSS.
<type-or-unit>
Is a keyword representing either the type of the attribute's value, or its unit, as in HTML some attributes have implicit units. If the use of <type-or-unit> as a value for the given attribute is invalid, the attr() expression will be invalid too. If omitted, it defaults to string. The list of valid values are:
Ключевое слово Тип Комментарий Значение по умолчанию
string <string> The attribute value is treated as a CSS <string>.  It is NOT reparsed, and in particular the characters are used as-is instead of CSS escapes being turned into different characters. An empty string
color <color> The attribute value is parsed as a hash (3- or 6-value hash) or a keyword. It must be a valid CSS <string> value.
Leading and trailing spaces are stripped.
currentColor
url <uri> The attribute value is parsed as a string that is used inside a CSS url()function.
Relative URL are resolved relatively to the original document, not relatively to the style sheet.
Leading and trailing spaces are stripped.
The url about:invalid that points to a non-existent document with a generic error condition.
integer <integer> The attribute value is parsed as a CSS <integer>. If it is not valid, that is not an integer or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
number <number> The attribute value is parsed as a CSS <number>. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
length <length> The attribute value is parsed as a CSS <length> dimension, that is including the unit (e.g. 12.5em). If it is not valid, that is not a length or out of the range accepted by the CSS property, the default value is used.
If the given unit is a relative length, attr()computes it to an absolute length.
Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
em, ex, px, rem, vw, vh, vmin, vmax, mm, cm, in, pt, or pc <length> The attribute value is parsed as a CSS <number>, that is without the unit (e.g. 12.5), and interpreted as a <length> with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
If the given unit is a relative length, attr()computes it to an absolute length.
Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
angle <angle> The attribute value is parsed as a CSS <angle> dimension, that is including the unit (e.g. 30.5deg). If it is not valid, that is not an angle or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0deg, or, if 0deg is not a valid value for the property, the property's minimum value.
deg, grad, rad <angle> The attribute value is parsed as a CSS <number>, that is without the unit (e.g. 12.5), and interpreted as an <angle> with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0deg, or, if 0deg is not a valid value for the property, the property's minimum value.
time <time> The attribute value is parsed as a CSS <time> dimension, that is including the unit (e.g. 30.5ms). If it is not valid, that is not a time or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0s, or, if 0s is not a valid value for the property, the property's minimum value.
s, ms <time> The attribute value is parsed as a CSS <number>, that is without the unit (e.g. 12.5), and interpreted as an<time> with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0s, or, if 0s is not a valid value for the property, the property's minimum value.
frequency <frequency> The attribute value is parsed as a CSS <frequency> dimension, that is including the unit (e.g. 30.5kHz). If it is not valid, that is not a frequency or out of the range accepted by the CSS property, the default value is used. 0Hz, or, if 0Hz is not a valid value for the property, the property's minimum value.
Hz, kHz <frequency> The attribute value is parsed as a CSS <number>, that is without the unit (e.g. 12.5), and interpreted as a <frequency> with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
Leading and trailing spaces are stripped.
0Hz, or, if 0Hz is not a valid value for the property, the property's minimum value.
% <percentage> The attribute value is parsed as a CSS <number>, that is without the unit (e.g. 12.5), and interpreted as a <percentage>. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
If the given value is used as a length, attr()computes it to an absolute length.
Leading and trailing spaces are stripped.
0%, or, if 0% is not a valid value for the property, the property's minimum value.
<fallback>
The value to be used if the associated attribute is missing or contains an invalid value. The fallback value must be valid where attr() is used, even if it is not used, and must not contain another attr() expression. If attr() is not the sole component value of a property, its <fallback> value must be of the type defined by <type-or-unit>. If not set, CSS will use the default value defined for each <type-or-unit>.

Формальный синтаксис

attr( <attr-name> <type-or-unit>? [, <attr-fallback> ]? )

где
<type-or-unit> = string | color | url | integer | number | length | angle | time | frequency | cap | ch | em | ex | ic | lh | rlh | rem | vb | vi | vw | vh | vmin | vmax | mm | Q | cm | in | pt | pc | px | deg | grad | rad | turn | ms | s | Hz | kHz | %

Пример

p::before {
  content: attr(data-foo) " ";
}
<p data-foo="hello">world</p>

Результат

Спецификации

Specification Status Comment
CSS Values and Units Module Level 3
Определение 'attr()' в этой спецификации.
Кандидат в рекомендации Added two optional parameters; can be used on all properties; may return other values than <string>. These changes are experimental and may be dropped during the CR phase if browser support is too small.
CSS Level 2 (Revision 1)
Определение 'attr()' в этой спецификации.
Рекомендация Limited to the content property; always return a <string>.

Совместимость с браузерами

Update compatibility data on GitHub
КомпьютерыМобильные
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome для AndroidFirefox для AndroidOpera для AndroidSafari on iOSSamsung Internet
counters()Chrome Полная поддержка ДаEdge Полная поддержка 12Firefox Полная поддержка 1.5IE Полная поддержка 8Opera Полная поддержка ДаSafari Полная поддержка ДаWebView Android Полная поддержка ДаChrome Android Полная поддержка ДаFirefox Android Полная поддержка 4Opera Android Полная поддержка ДаSafari iOS Полная поддержка ДаSamsung Internet Android Полная поддержка Да
<fallback>
Экспериментальная
Chrome Нет поддержки НетEdge Нет поддержки НетFirefox Нет поддержки НетIE Нет поддержки НетOpera Нет поддержки НетSafari Нет поддержки НетWebView Android Нет поддержки НетChrome Android Нет поддержки НетFirefox Android Нет поддержки НетOpera Android Нет поддержки НетSafari iOS Нет поддержки НетSamsung Internet Android Нет поддержки Нет
<type-or-unit>
Экспериментальная
Chrome Нет поддержки НетEdge Нет поддержки НетFirefox Нет поддержки НетIE Нет поддержки НетOpera Нет поддержки НетSafari Нет поддержки НетWebView Android Нет поддержки НетChrome Android Нет поддержки НетFirefox Android Нет поддержки НетOpera Android Нет поддержки НетSafari iOS Нет поддержки НетSamsung Internet Android Нет поддержки Нет

Легенда

Полная поддержка  
Полная поддержка
Нет поддержки  
Нет поддержки
Экспериментальная. Ожидаемое поведение может измениться в будущем.
Экспериментальная. Ожидаемое поведение может измениться в будущем.

Метки документа и участники

Внесли вклад в эту страницу: mdnwebdocs-bot, SphinxKnight, palchikowa, andreww2012
Обновлялась последний раз: mdnwebdocs-bot,