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. 
</div>

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
attr()
by JS Craft (@js-craft)
on CodePen.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X