omega omega - 5 months ago 10
CSS Question

How to select any element that has an attribute equal to red in css3?

If I want all

div
s that has attribute
data-color
equal to
red
, I can do

div[data-color='red']


But what if I want any element at all, that has
data-color
equal to
red
?

How would I write that?

Answer

Use that same attribute selector, but without any element before attached to it

Represents an element with an attribute name of attr and whose value is exactly "value".

It will select any element with the [data-color='red']

Note: even using the '' which they are different then "", but it will select they "" anyhow.

[data-color='red'] {
  background: red;
  display: block
}
<div data-color='red'>red</div>
<p data-color='red'>red</p>
<article data-color='red'>red</article>
<section data-color='red'>red</section>
<h1 data-color='red'>red</h1>
<span data-color='red'>red</span>

<hr />

<div data-color="red">red</div>
<p data-color="red">red</p>
<article data-color="red">red</article>
<section data-color="red">red</section>
<h1 data-color="red">red</h1>
<span data-color="red">red</span>

If you want to target a specific element you can just put that element before the attribute selector:

div[data-color='red'] {
  background: red;
}
p[data-color='red'] {
  color: red
}
<div data-color='red'>red</div>
<p data-color='red'>red</p>