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:
📖 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.