How to Retrieve Attribute Values in CSS
Use the attr()
property in CSS if you want to retrieve the value of an element's attribute and use it in your stylesheets:
Copied to clipboard! Playground
<span data-icon="πΊ" data-name="Hibiscus"></span>
<style>
span::before {
content: attr(data-name);
}
</style>
In the example above, the value of the attr()
funcion will be "Hibiscus". You can also specify types to attr()
, using the following way:
Copied to clipboard! Playground
.types {
attr(data-src url); /* Define type as url */
attr(data-score number); /* Define type as number */
attr(data-width px); /* Define type as pixel */
}
By using a second parameter, you also have the ability to provide fallback values:
Copied to clipboard! Playground
.defaults {
attr(data-src url, ''); /* Will fallback to an empty string */
attr(data-width px, inherit); /* Will fallback to the inherited property */
attr(data-name, 'Unknown'); /* Will fallback to "Unknown" */
}
Resources:
π More Webtips
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:
Courses
CSS - The Complete Guide (including Flexbox, Grid and Sass)
Including Flexbox, Grid, and Sass
Whether you're learning CSS for the first time or brushing up on your CSS skills and diving even deeper, this course is for you. Every web developer has to know CSS.
The HTML & CSS Bootcamp
From Zero to Expert!
This course covers flexbox, CSS grid, animations, responsive design, and much more! You will find tons of exercises & projects inside this course.
The Creative HTML5 & CSS3 Course
Build Awesome Websites
Learn HTML5 and CSS3 by creating three amazing, well-designed and animated websites from scratch.