Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

What is the CSS attr() function and how it can help us

In CSS we can use the attr() function in our stylesheets, to get the value of an attribute from a HTML element and use it in the ::before or ::after pseudo-elements.

So, let say that we have:

<div data-myattribute="some value">
    Text of the div here. 

Then we can use the attr() function to read the value of data-myattribute and set it in the content of a before pseudo-element.

div::before {
    content: " (" attr(data-myattribute) ")";
    color: green;

The usage of the attr() function is not bounded only to data- attributes. For example, we cause it to read the value of the href and display a tooltip with that value when someone hovers any link in our site:

a::after {
    content: attr(href);
    position: absolute;
    top: 0;
    left: 0;
    background: #000;
    color: #fff;
    text-align: center;
    display: none;
a:hover::after {
    display: block;

All of this without even one single line of Javascript. Check out the full working codepen below:

See the Pen
by JS Craft (@js-craft)
on CodePen.

Home Screencasts Best of Newsletter Search X