Matt.
Matt.

Reputation: 1294

If element has specific CSS class and also ANY other class

I can't believe I've never had to do this before in my long time writing CSS but this has me stumped.

I have span.item-name and I want to add some specific styles only if this element has another class, which could be ANY class.

I've tried span.item-name.* and it doesn't do the trick. Is this possible and what are my options?

Upvotes: 1

Views: 5510

Answers (3)

G-Cyrillus
G-Cyrillus

Reputation: 105903

you can use the attribute selector. (see: https://www.w3.org/wiki/CSS/Selectors#Attribute_Selector ) example:

body>.item-name:before, b {
  content:'Class name is: 'attr(class)'. ';
  color:purple
}
p[class*="item-name"][class*=" "]:before {
  color:green;
}
p[class^="item-name"][class*=" "]:before {
  color:red;
}
<p class="item-name"> The basic class</p>
<p class="item-name another-class"> the basic class at first and then any other</p>
<p class="another-class item-name  any-more-class"> more than one class including <b>item-name</b> at any position</p>

Upvotes: 2

RompePC
RompePC

Reputation: 835

I think this is what you want, scroll until you see the CSS [attribute*="value"] Selector section. For you it should be something like:

span[class*=" item-name"], span[class*="item-name "]

Why two selectors? Because *= search for that specific value, so only with the first selector <span class="item-name another-class"> would not meet the criteria. That way you just search for the class, being unaware of its position in the class value.

Upvotes: 2

hjcoder18
hjcoder18

Reputation: 479

Maybe some more code will help, but you can't write functions for css, which it sounds like what you are asking for. You can simply just add another class if you need to.

<span class="class1 class2">

Upvotes: -1

Related Questions