Display HTML5 data-attribute with CSS

In this tutorial we’re going to take a look at how can we display the content of the HTML5 data attribute with CSS

In a previous tutorial, we took a look at how to use the html5 data attribute as selectors in jQuery. In this one, we’ll take a look at how can we display the content of the data-attributes with CSS. We can display them ::before and ::after an element, using the CSS content property.

The HTML

First off, we’ll create an html element that has a data-attribute, then we’ll use css to display it’s value.

<a data-link="This is a dummy Link - " href="#">
    I have data attribute
</a>

As you can see, we have a dummy link that doesn’t go anywhere. We also have a data-link=”” with some dummy content. The name of the data attribute can be anything, untill it starts with  ” data- “.

The CSS

Here I’ll show you two methods you can display the content of these data attributes.

Targeting the element itself

The first method, doesn’t check if the element actually has the data attribute added or not :

a::before {
    content: attr(data-link);
    color: #000;
}

As you can see, we used the content css property, and the attr() value with the name of our data attribute inside it. This will add the content of data-link=”” before the element. So now, it should look something like this:

See the Pen GpqYXv by Andor Nagy (@andornagy) on CodePen.

Targeting the data-attribute The second method is, that we use the data attribute itself as a selector. So if we use the same HTML link as before, and use the following CSS:

[data-link]::before {
    content: attr(data-link);
    color: #000;
}

This will look for elements  that selects all the anchor elements, this one only selects the ones that have the data-link attribute.

See the Pen vNKVQm by Andor Nagy (@andornagy) on CodePen.

As you can see, the first link, that has data-link attribute, has additional content before it, but the second one doesn’t.

I hope this short tutorial helps you understand how to display the html5 data-attribute with css. This can be used for a ton of things, for example responsive tables to display the column titles and what not. But that’s for an other tutorial.