We previously looked at using data attributes in JavaScript. These data attributes are a fantastic way to store little bits of information on an element without using custom attributes.
However, we can also use them to style some aspects with specific attribute sets.
CSS attributes in CSS
To paint a simple picture, let's create elements that hold a specific value like this.
<div data-rating="1">Rating</div>
<div data-rating="5">Rating</div>
As you can see, our rating is only set as the custom attribute.
Let's first look at how we can style this object, which is very easy by simply using its name.
[data-rating] {
color: indigo;
}
With this, the rating text will be purple.
We can also make it more specific and add styling for particular values.
[data-rating='1'] {
color: red;
}
[data-rating='5'] {
color: indigo;
}
And to top it off, we can inject the value with CSS!
[data-rating]::after {
content: attr(data-rating);
}
Which would result in the rating being added after our text.
You can play with these data attributes on the following CodePen.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Top comments (8)
This:
is amazing!
But not accessible and should not be used in production
Yeah not surprising, it's a bit of a hack of course, it's clever but let's not get carried away :)
Hacks are fine as long as we know they are, fixing them later or closing the gap now, great power great responsibility etc etc π
Oh yeah π₯³
data-tag use case is most important in react becaouse this is help to avoid over load className aka class and result is much cleaner code.
for example:
FYI: There is a school of thought that data attributes should not be bound to (i.e. targeted in CSS).
cssguidelin.es:
This refers to 3.2.6.6 Embedding custom non-visible data with the
data-*
attributes of the HTML living standard.From that perspective using attribute selectors with data attributes is primarily helpful for
document.querySelector()
.Using this technique, ban yourself from describing UI states where possible and use aria instead, then style with aria. The result you write accessible code that must be thought out in order to be styled