简体   繁体   English

如果element有特定的CSS类,也有任何其他类

[英]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. 在我很长一段时间写CSS之前,我无法相信我从来没有这样做过,但这让我很难过。

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. 我有span.item-name ,我想添加一些特定的样式,只有当这个元素有另一个类时,它可以是任何类。

I've tried span.item-name.* and it doesn't do the trick. 我已经尝试过span.item-name.*并且它没有做到这一点。 Is this possible and what are my options? 这可能吗?我的选择是什么?

you can use the attribute selector. 您可以使用属性选择器。 (see: https://www.w3.org/wiki/CSS/Selectors#Attribute_Selector ) example: (参见: https//www.w3.org/wiki/CSS/Selectors#Attribute_Selector示例:

 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> 

I think this is what you want, scroll until you see the CSS [attribute*="value"] Selector section. 我想就是你想要的,滚动直到你看到CSS [attribute * =“value”]选择器部分。 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. 因为*=搜索该特定值,所以只有第一个选择器<span class="item-name another-class">才符合条件。 That way you just search for the class, being unaware of its position in the class value. 这样你只需要搜索类,不知道它在class值中的位置。

Maybe some more code will help, but you can't write functions for css, which it sounds like what you are asking for. 也许更多的代码会有所帮助,但你不能为css编写函数,这听起来像你要求的。 You can simply just add another class if you need to. 如果需要,您可以简单地添加另一个类。

<span class="class1 class2">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM