CSS attr() Function

CSSPosted on

Using attr() function in our stylesheets, we can get any attribute from any HTML element and display it in the ::before or ::after pseudo-element.

We can get attributes like the href, which is necessary in the case of anchor tags or custom ones like a data-*.

Currently, the attr() is a little bit limited; we can only use it to display values in pseudo-elements. There is two everyday use case which worth to mention.

Display the URL on a Print Page

If you want to print a web page, you will have a simple problem with the links. By default, you can’t see the URL where the link is pointing. To solve this issue, we can use the attr() to display its value after/in the <a> tag like so:

@media print { 
    a[href]::after {  
        content: " (" attr(href) ")";

This is a cool feature which makes the text more usable for anyone who wants to print it.

Create a Tooltip Solutions

If you want to develop a simple tooltip solution, the attr() function can play a crucial part in it. Using it, we can display the declared text from an HTML element – handled dynamically – and display in ::before or ::after pseudo-element. 

We can’t handle any more function beside the display and hide through CSS but still can be handy in a lot of situation.

See the Pen
Pure CSS Tooltip
by Adam Laki (@adamlaki)
on CodePen.

The Future of the attr()

The attr() function will work differently from the level 3 CSS specification, but currently, it isn’t supported well.

If it moves from candidate to recommendation we will get the following syntax:

attr( <attr-name> <type-or-unit>? [, <attr-fallback> ]? )

The first param is the name, the second is the unit, which means we can get back various types of values like color, length, number. Besides, it will be usable on all of the CSS properties so we can declare color values with it.

For more information about the CSS3 attr() function, please visit MDN! 

Need a web developer? Maybe we can help, get in touch!

Similar Posts

More content in CSS category