attr() CSS Function
Description
The CSS attr()
function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can be used with any CSS property, but support for properties other than content
is experimental.
The attr()
function takes a single parameter, which is the name of the attribute to retrieve. The value of the attribute is then returned as a string. If the attribute is missing or has an invalid value, the empty string is returned.
Here is an example of how to use the attr()
function:
/* Set the width of an element to the value of its `data-width` attribute. */
.element {
width: attr(data-width);
}
If the element has a data-width
attribute with the value "100px", then the width
property of the element will be set to 100 pixels.
The attr()
function can also be used to create dynamic effects. For example, you could use it to create a tooltip that displays the value of an element's title
attribute when the user hovers over the element.
Here is an example of how to do this:
/* Create a tooltip element. */
.tooltip {
position: absolute;
display: none;
background-color: white;
padding: 5px;
border: 1px solid black;
}
/* Show the tooltip when the user hovers over the element. */
.element:hover .tooltip {
display: block;
}
/* Set the content of the tooltip to the value of the element's `title` attribute. */
.tooltip::after {
content: attr(title);
}
This will create a tooltip that appears when the user hovers over the element, and the tooltip will display the value of the element's title
attribute.
The attr()
function is a powerful tool that can be used to create a variety of dynamic effects in your CSS.
Syntax
attr( <attr-name> <type-or-unit>? [ , <attr-fallback> ]? )
Values
- <attr-name>Is the name of an attribute on the HTML element referenced in the 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. The following keywords are valid: <string>, <color>, <url>, <integer>, <number>, <angle>, <time>, <deg>, and also CSS units like em, ex, px, rem, vw, vh, vmin, vmax, mm, cm, in, pt, or pc
- <attr-fallback>The value that will be used if the attribute is absent or the browser cannot receive it.
Example
<p>The attr() Function</p>
<a href="https://www.cssportal.com">CSSPortal</a>
a:before {
content: attr(href) " -> ";
}
a {
text-decoration: none;
}
Browser Support
The following table will show you the current browser support for the CSS attr()
function.
Desktop | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
|
12 | 2 | 1 | 9 | 3.1 |
Tablets / Mobile | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
18 | 4 | 10.1 | 2 | 1 | 37 |
Last updated by CSSPortal on: 7th October 2023