How to style HTML elements tags using any attributes in CSS?

July 21, 2021 - 2 min read

To style HTML element tags using any attributes, you can use the [] (square brackets) and then write the name of the attribute you are targetting inside the square brackets in the CSS stylesheet.

For example, let's consider a p (paragraph) HTML element tag with a custom attribute called data-number with a value of 1.

It will look like this in HTML,

<!-- Paragraph tag with custom attribute of "data-number" -->
<p data-number="1">Hello World!</p>

Now to style the HTML element using the custom attribute you can use the square brackets and then write the name of the custom attribute with the value inside the square brackets in CSS.

Let change the text color of the paragraph to a red color.

It can be done like this,

/* 
Style HTML element tag having 
the custom attribute of "data-number" and value of "1" 
*/
[data-number="1"] {
  color: red;
}

Now the paragraph tag's text color is changed to red.

See the above code live in JSBin.

How to select HTML element tags using the custom attribute irrespective of the attribute value?

Let's now add another paragraph with the same custom attribute data-number but now the value of it is changed to 2 like this,

<!-- Paragraph tags with custom attribute of "data-number" -->
<p data-number="1">Hello World!</p>
<p data-number="2">Hello Devs!</p>

Now if you look at the output you can see that only the first paragraph with data-number="1" has the text color changed to red. This is because we are strictly targeting elements with the custom attribute of data-number and the value of 1.

Our aim here is to target all those elements those having the custom attribute data-number, to do that we can just omit the part after the = (equal sign) leaving only the name of the custom attribute inside the CSS.

It can be done like this,

/* 
Style HTML element tag having 
the custom attribute of "data-number"
*/
[data-number] {
  color: red;
}

Now all the HTML element tags having the custom attribute of data-number text color are changed to red irrespective of the attribute's value.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.