Css получить атрибут элемента

attr()

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

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

/ * Простое использование * / 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");

Syntax

Values

Имя атрибута элемента HTML,на который ссылается CSS.

Ключевое слово, представляющее либо тип значения атрибута, либо его единицу, поскольку в HTML некоторые атрибуты имеют неявные единицы. Если использование в качестве значения для данного атрибута недопустимо, выражение attr() также будет недействительным. Если опущено, по умолчанию используется string . Список допустимых значений:

Значение по умолчанию:пустая строка.

Значение атрибута анализируется как хэш (хэш с 3 или 6 значениями) или ключевое слово. Это должно быть допустимое значение CSS . Начальные и конечные пробелы удаляются.

Значение по умолчанию: currentcolor .

Значение атрибута анализируется как строка, которая используется внутри функции url() CSS . Относительные URL-адреса разрешаются относительно исходного документа, а не относительно таблицы стилей. Начальные и конечные пробелы удаляются.

Значение по умолчанию: URL-адрес about:invalid , указывающий на несуществующий документ с общей ошибкой.

Значение по умолчанию: 0 или, если 0 не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0 или, если 0 не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0 или, если 0 не является допустимым значением для свойства, минимальное значение свойства.

em , ex , px , rem , vw , vh , vmin , vmax , mm , cm , in , pt или pc Experimental

Значение по умолчанию: 0 или, если 0 не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0deg , или, если 0deg не является допустимым значением для свойства, минимальное значение свойства.

deg , grad , rad Experimental

Значение по умолчанию: 0deg , или, если 0deg не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0s или, если 0s не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0s или, если 0s не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0Hz или, если 0Hz не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0Hz или, если 0Hz не является допустимым значением для свойства, минимальное значение свойства.

Значение по умолчанию: 0% или, если 0% не является допустимым значением для свойства, минимальное значение свойства.

Значение, которое будет использоваться, если связанный атрибут отсутствует или содержит недопустимое значение. Если не установлен, CSS будет использовать значение по умолчанию, определенное для каждого .

Formal syntax

 = attr( q-name> attr-type>? , declaration-value>? ) attr-type> = string | url | ident | color | number | percentage | length | angle | time | frequency | flex | dimension-unit> 

Examples

content property

HTML

Источник

Читайте также:  Javascript and or operator logical

attr

С помощью функции 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.
    • : Является ключевым словом, представляющим либо тип значения атрибута, либо его единицу, так как в HTML некоторые атрибуты имеют неявные единицы. Если использование в качестве значения для данного атрибута недопустимо, выражение attr() также будет недопустимым. Если этот параметр опущен, по умолчанию используется string . Список допустимых значений: Ключевое слово Тип Комментарий Значение по умолчанию
      string (en-US) The attribute value is treated as a CSS (en-US). 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 Экспериментальная возможность The attribute value is parsed as a hash (3- or 6-value hash) or a keyword. It must be a valid CSS (en-US) 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 . 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 Экспериментальная возможность The attribute value is parsed as a CSS . 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 Экспериментальная возможность The attribute value is parsed as a CSS 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 Экспериментальная возможность The attribute value is parsed as a CSS , that is without the unit (e.g. 12.5 ), and interpreted as a 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 Экспериментальная возможность The attribute value is parsed as a CSS 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 Экспериментальная возможность The attribute value is parsed as a CSS , that is without the unit (e.g. 12.5 ), and interpreted as an 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 Экспериментальная возможность The attribute value is parsed as a CSS 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 Экспериментальная возможность The attribute value is parsed as a CSS , that is without the unit (e.g. 12.5 ), and interpreted as an 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 Экспериментальная возможность (en-US) The attribute value is parsed as a CSS (en-US) 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 Экспериментальная возможность (en-US) The attribute value is parsed as a CSS , that is without the unit (e.g. 12.5 ), and interpreted as a (en-US) 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.
      % Экспериментальная возможность The attribute value is parsed as a CSS , that is without the unit (e.g. 12.5 ), and interpreted as a . 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.
    • : 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 value must be of the type defined by . If not set, CSS will use the default value defined for each .

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

    =
    attr( ? (en-US) , ? (en-US) )

    =
    string | (en-US)
    url | (en-US)
    ident | (en-US)
    color | (en-US)
    number | (en-US)
    percentage | (en-US)
    length | (en-US)
    angle | (en-US)
    time | (en-US)
    frequency | (en-US)
    flex | (en-US)

    Пример

    p::before  content: attr(data-foo) " "; > 

    Источник

    The CSS attr() Function

    The CSS attr() Function

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

    attr() is a CSS function that returns the value of a property. That means that you can define content in your html markup using any custom property and then fetch the value using attr(). It only works on the content property at the moment, but support for other properties are currently in the experimental stage. An example should help explain. First, the HTML markup:

    span data-tooltip="Cascading Style Sheets">CSSspan> 
    [data-tooltip]::before  content: attr(data-tooltip); > 

    And with this you can create custom tooltips in pure CSS. Browser Support 👉 Browser info is for properties other than content. attr() works across all browsers for content. Can I Use css3-attr? Data on support for the css3-attr feature across the major browsers from caniuse.com.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

    Источник

Оцените статью