attr
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Описание
С помощью функции 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>
Экспериментальная возможность-
Является ключевым словом, представляющим либо тип значения атрибута, либо его единицу, так как в HTML некоторые атрибуты имеют неявные единицы. Если использование
<type-or-unit>
в качестве значения для данного атрибута недопустимо, выражениеattr()
также будет недопустимым. Если этот параметр опущен, по умолчанию используется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Значение по умолчанию: An empty string
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
Экспериментальная возможность-
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
Экспериментальная возможность-
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, if0
is not a valid value for the property, the property's minimum value. 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, if0
is not a valid value for the property, the property's minimum value. 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, if0
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
, orpc
Экспериментальная возможность-
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, if0
is not a valid value for the property, the property's minimum value. 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, if0deg
is not a valid value for the property, the property's minimum value. deg
,grad
,rad
Экспериментальная возможность-
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, if0deg
is not a valid value for the property, the property's minimum value. 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, if0s
is not a valid value for the property, the property's minimum value. s
,ms
Экспериментальная возможность-
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, if0s
is not a valid value for the property, the property's minimum value. 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, if0Hz
is not a valid value for the property, the property's minimum value. Hz
,kHz
Экспериментальная возможность-
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, if0Hz
is not a valid value for the property, the property's minimum value. %
Экспериментальная возможность-
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, if0%
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 anotherattr()
expression. Ifattr()
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( <attr-name> <attr-type>? , <declaration-value>? )
<attr-name> =
[ <ident-token>? '|' ]? <ident-token>
<attr-type> =
type( <syntax> ) |
string |
<attr-unit>
<syntax> =
'*' |
<syntax-component> [ <syntax-combinator> <syntax-component> ]* |
<syntax-string>
<syntax-component> =
<syntax-single-component> <syntax-multiplier>? |
'<' transform-list '>'
<syntax-combinator> =
'|'
<syntax-string> =
<string>
<syntax-single-component> =
'<' <syntax-type-name> '>' |
<ident>
<syntax-multiplier> =
'#' |
'+'
<syntax-type-name> =
angle |
color |
custom-ident |
image |
integer |
length |
length-percentage |
number |
percentage |
resolution |
string |
time |
url |
transform-function
Пример
p::before {
content: attr(data-foo) " ";
}
<p data-foo="hello">world</p>
Результат
Спецификации
Specification |
---|
CSS Values and Units Module Level 5 # attr-notation |
Совместимость с браузерами
BCD tables only load in the browser