css匹配选择器与相邻类限制

时间:2015-07-19 20:11:47

标签: css css3 css-selectors

当我想匹配特定类my-class-b时,我可以在同一个元素上使用另一个类my-other-class-a

.my-class-b.my-other-class-a {
}

此外,当我想通过部分类名匹配时,我可以使用

[class^="my-class-"] {
}

现在我想混合两者,但它似乎没有效果。我该怎么办

[class^="my-class-"].my-other-class-a {
}

3 个答案:

答案 0 :(得分:8)

这是因为在css选择器[class^="abc"]中测试了class属性的开头。

如果选择器是

[class^="my-"]

然后

class="my-class red"

不同
class="red my-class"

http://jsfiddle.net/u5sfge94/

上查看

解决此问题的一种方法是指定一个充当[class ^ =" abc"]的新类。它可以使你的样式表更有条理,你的代码更清晰,css渲染速度更快。

答案 1 :(得分:5)

前一个答案中对@juank的解释是正确的:你编写类的顺序很重要,因为^代表值的开头。

但是还有许多其他属性选择器使用 regexp 表示法:^=*=$=; RESP。以匹配开头,随时随地 如果您希望您的选择器匹配包含my-class的类,则应使用*=(请参阅 Snippet 1 )。 但是它也会匹配任何不以my-class开头但仍包含它的类。为避免这种情况,您可以像以前一样使用^=进行匹配,也可以匹配[class*=" my-class"](带空格):它会考虑不是第一个写入的类的情况class属性的值(请参阅 Snippet 2 )。

CSS3info中的

资源: CSS3 Substring Matching Attribute Selectors(最后链接到 REC CSS 3级选择器

代码段1:

[class*='my-class'].my-other-class-a {
  background-color: lightgreen;
}
<div class="my-class-a my-other-class-a">Should match 1</div>
<div class="my-class-b my-other-class-a">Should match 2</div>
<div class="my-other-class-a">Nope</div>
<div class="my-other-class-a my-class-a">Should match 3</div>
<div class="my-other-class-a my-class-b">Should match 4</div>
<div class="whatever my-other-class-a my-class-a">Should match 5</div>
<div class="other my-other-class-a my-class-b">Should match 6</div>
<div class="my-other-class-a maybe-maybe-not-my-class-a">Beware</div>

代码段2:

[class^='my-class'].my-other-class-a,
[class*=' my-class'].my-other-class-a {
  background-color: lightgreen;
}
<div class="my-class-a my-other-class-a">Should match 1</div>
<div class="my-class-b my-other-class-a">Should match 2</div>
<div class="my-other-class-a">Nope</div>
<div class="my-other-class-a my-class-a">Should match 3</div>
<div class="my-other-class-a my-class-b">Should match 4</div>
<div class="whatever my-other-class-a my-class-a">Should match 5</div>
<div class="other my-other-class-a my-class-b">Should match 6</div>
<div class="my-other-class-a maybe-maybe-not-my-class-a">Beware</div>

答案 2 :(得分:1)

这不完全是防弹,但只要您的“变量”类是第一个,这可以起作用:

div[class^='my-class'][class~='my-other-class-a'] {
  background-color: red;
}
<div class="my-class-a my-other-class-a">Hello</div>
<div class="my-class-b my-other-class-a">World</div>
<div class="my-other-class-a">Bye</div>