logo
post image

Using Data-Attributes (data-*) in CSS

A special thing about HTML data-attributes is that its values can be directly rendered through CSS also.

Whenever content in a page changes, the usual process is to show the changed content through Javascript (appening new HTML). But this can be alternatively done by using data-attributes in CSS — whenever value of data-attribute changes, the new value is rendered automatically in the page.

Data-Attributes in CSS

Data-attributes can be read in CSS using the content property. The content CSS property can be used only on ::before and ::after pseudo-elements.

<div id="container" data-point="14">Post 1</div>
/* content of pseudo-element will be set to the current value of "data-point" */
#container::before {
	content: attr(data-point);
}

In the above example whenever value of data-point changes, the rendered content of #container::before will be changed to the new value of the attribute.

You can also set specific CSS properties when the value of the data-attribute equals a specific value.

/* content of pseudo-element will be set to the current value of "data-point" */
#container::before {
	content: attr(data-point);
}

/* set color of pseudo-element to red when data-point=50 */
#container[data-point="50"]::before {
	color: red;
}

An Example Video

The below screencast shows a sample example on how data-attributes can be used in CSS to improve efficiency of rendered content.