Css content before attr

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) " "; > 

    Источник

    attr ( )

    Хотите сделать атрибут элемента видимым на странице? Используйте эту функцию!

    Время чтения: меньше 5 мин

    Кратко

    Скопировать ссылку «Кратко» Скопировано

    attr ( ) — это CSS-функция, которая умеет получать значение любого атрибута элемента, а потом использовать это значение прямо в стилях.

    Пример

    Скопировать ссылку «Пример» Скопировано

     div class="element" title="На самом деле внутри нет никакого текста">div>      
     div::before  content: "Элемент с классом " attr(class);> div::after  content: "Подсказка: " attr(title);> div::before  content: "Элемент с классом " attr(class); > div::after  content: "Подсказка: " attr(title); >      

    Как пишется

    Скопировать ссылку «Как пишется» Скопировано

     div::before  content: attr(data-title); content: attr(href);> div::before  content: attr(data-title); content: attr(href); >      
     div::before  content: attr(src url); content: attr(data-count number); content: attr(data-width px);> div::before  content: attr(src url); content: attr(data-count number); content: attr(data-width px); >      

    С указанием фолбэка, то есть запасного значения:

     div::before  content: attr(data-count number, 0); content: attr(src url, ""); content: attr(data-width px, inherit); content: attr(data-something, "default");> div::before  content: attr(data-count number, 0); content: attr(src url, ""); content: attr(data-width px, inherit); content: attr(data-something, "default"); >      

    Подсказки

    Скопировать ссылку «Подсказки» Скопировано

    💡 Функцию attr ( ) можно использовать в качестве значения любого CSS-свойства, однако полностью поддерживается только свойство content . Для остальных свойств поддержка экспериментальная и может различаться от браузера к браузеру. Актуальную информацию о поддержке можно посмотреть на Can I use.

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

     .colored  background-image: attr(data-src url);> .colored  background-image: attr(data-src url); >      

    Тут мы указали, что в качестве значения для свойства background — image мы хотим использовать значение атрибута data — src . При этом уточнили, что значение атрибута data — src — это не просто строка, а корректный URL.

    Примеры записи с указанием типа или фолбэка кажутся довольно перспективными, но, к сожалению, пока не поддерживаются ни одним из браузеров.

    На практике

    Скопировать ссылку «На практике» Скопировано

    Денис Ежков советует

    Скопировать ссылку «Денис Ежков советует» Скопировано

    🛠 Самый распространённый случай использования функции attr ( ) — отображение значения атрибута href после текста ссылки при печати страницы.

       Подробнее о скидках и акциях можно узнать по ссылке  p> Подробнее о скидках и акциях можно узнать a href="http://best-site.ru/sales">по ссылкеa> p>      
     @media print  a::after  content: " [" attr(href) "]"; >> @media print  a::after  content: " [" attr(href) "]"; > >      

    Источник

    Читайте также:  Ubuntu apache nginx php fpm
Оцените статью