CSS类选择器通配符 [英] CSS class selector wildcard

查看:102
本文介绍了CSS类选择器通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道是否可以将通配符放入CSS?

So I was wondering if there was a way to throw a wildcard into my CSS?

我在button元素中有几个类,分别是.button-0.button-1.button-2.button-3等.我想获取所有要定义的.button-*类.

I have several classes that are .button-0, .button-1, .button-2, .button-3, etc. within a button element. I want to get all the .button-* classes to define.

是否可以做类似的事情:

Is it possible to do something like:

button .button-[=*] {
  margin-right: 2rem;  
}

推荐答案

使用

此处的示例

来自 MDN :

[attr*=value]-表示一个属性名称为attr且其值包含至少一个出现的字符串"value"作为子字符串的元素.

[attr*=value] - Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

button [class*="button-"] {
  color: red;
}

<button>
    <span class="button-0">text</span>
    <span class="button-1">text</span>
    <span class="button-2">text</span>
</button>

乍得指出,这完全有可能元素可以包含诸如this-is-my-button-class之类的类.在这种情况下,将选择该不需要的元素.为了防止这种情况,您可以结合使用两个选择器:

As Chad points out, it is entirely possible that an element can contain a class such as this-is-my-button-class. In which case, that undesired element would be selected. In order to prevent this, you could use a combination of two selectors:

此处的示例

button [class^="button-"],
button [class*=" button-"] {
  margin-right: 2rem;  
}

选择器button [class^="button-"]确保以button-开头的元素将被选择.由于该元素的第一类可能不是以button-开头的,因此选择器[class*=" button-"](请注意空白)可确保将其选中.

The selector button [class^="button-"] ensures that the element will be selected if it starts with button-. Since it's possible the element's first class doesn't start with button-, the selector [class*=" button-"] (note the whitespace), ensures that it will be selected.

这篇关于CSS类选择器通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆