omega
omega

Reputation: 43853

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

If I want all divs 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?

Upvotes: 1

Views: 1036

Answers (2)

dippas
dippas

Reputation: 60563

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 is different than ""), it will still select "" 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>

Upvotes: 7

mattpark22
mattpark22

Reputation: 751

You should be able to just use:

[data-color='red']

or you could write it this way:

*[data-color='red']

you can also write it with double quotes, this will also select the same but it's worth keeping to the same format throughout your CSS file to maintain standards. I would recommend sticking to single quotes in this case.

[data-color="red"]

This would select any HTML element with the data-color attribute value equal to red.

For example:

<div data-color='red'>Red</div>
<p data-color='red'>Red</p>
<span data-color='red'>Red</span>

Working example:

[data-color='red'] {
  background: red;
}
<div data-color='red'>Red</div>
<p data-color='red'>Red</p>
<span data-color='red'>Red</span>
<hr data-color='red'/>
<section data-color='red'>Red</section>
<article data-color='red'>Red</article>
<aside data-color='red'>Red</aside>

Upvotes: 5

Related Questions