CSS attr() Function
Get the value of an attribute with the CSS attr()
function.
The CSS attr()
function returns the value of an attribute of an element.
For example, you could use the attr()
function to return and display the title
attribute from an abbreviation. Like this:
Hyperlinks
Another potentially useful example is getting the text of a URL of a hyperlink:
As demonstrated here, you can add other text around the value (such as enclosing it in brackets, adding spaces, etc). You can also apply other styles to the generated content (such as making the text italic).
Printed Page Example
A common use of attr()
is for displaying hyperlinks on the printed version of the page (i.e. when the user prints the page). This can be achieved by placing it inside the @media
rule:
When the page is printed, each hyperlink element will have its full URL displayed next to the link text. If the URL is long, it will probably be displayed under the text link, as it will wrap to the next line.
Custom HTML5 Attributes
The attr()
function also works on custom HTML5 data attributes. For example:
If the attr()
references an attribute that's not present, the empty string is returned, as shown in this example.
CSS3 Additions
CSS3 adds the ability to apply the attr()
function against all properties (not just the content
property), and to also return non-string values (such as numbers, colors, etc).
CSS3 also provides the option of using a fallback value — a value that will be used which is used if the named attribute is missing, or its value cannot be parsed into the given type or is invalid/out-of-range for the property.
The CSS3 syntax goes like this:
This basically means that you can provide an (optional) unit or type, and an (optional) fallback value.
So you could do something like this:
This example takes a value from a custom data attribute called data-size
, adds em
as the unit, and applies it to the height
property. It also provides a fallback value of 20
which is used if the named attribute is missing or can't be used.
However, as of this writing, the CSS3 syntax is not supported in any major browser. You can continue to use the CSS2 syntax (as per the previous examples).
The Browser Support chart below shows the browsers that currently support the CSS3 implementation of attr()
.
CSS Specifications
- The
attr()
function is defined in CSS Values and Units Module Level 3 (W3C Candidate Recommendation, 29 September 2016) - It's also defined in Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification (W3C Recommendation 07 June 2011)
Browser Support
The following table provided by Caniuse.com shows the level of browser support for this feature.