CSS 匹配所有类名以特定字符串开头的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13352080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:45:11  来源:igfitidea点击:

Match all elements having class name starting with a specific string

css

提问by jchwebdev

Is it possible to use a "wildcard" for elements having a class name starting with a specific string in CSS3?

是否可以对类名以 CSS3 中的特定字符串开头的元素使用“通配符”?

Eg.:

例如。:

<div class="myclass-one"></div>
<div class="myclass-two></div>
<div class="myclass-three"></div>

and then magically set all the above divs to red in one go:

然后神奇地div一次性将上面的所有s设置为红色:

.myclass* { color: #f00; }

回答by Koen.

The following should do the trick:

以下应该可以解决问题:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}


Edit: Added wildcard (*) as suggested by David

编辑:*按照大卫的建议添加通配符 ( )

回答by James Montagne

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

这不是问题的直接答案,但是我建议在大多数情况下简单地为每个元素设置多个类:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclasselements and then more specific rules for one, twoand three.

通过这种方式,您可以为所有myclass元素设置规则,然后为one,two和设置更具体的规则three

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

回答by Andy

You can easily add multiple classes to divs... So:

您可以轻松地将多个类添加到 div... 所以:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

然后在对共享类的 CSS 调用中应用相同的样式:

.myclass {...}

And you can still use your other classes like this:

你仍然可以像这样使用你的其他类:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

或者,如果您想像这样在 CSS 中更具体:

.myclass.myclass-three {...}