当我想匹配特定类my-class-b
还具有另一个类my-other-class-a
同一元件上我能做到CSS匹配选择
.my-class-b.my-other-class-a {
}
此外,当欲通过部分类名我匹配可以使用
[class^="my-class-"] {
}
现在我想混合两者,但它似乎并没有工作。我该怎么办
[class^="my-class-"].my-other-class-a {
}
当我想匹配特定类my-class-b
还具有另一个类my-other-class-a
同一元件上我能做到CSS匹配选择
.my-class-b.my-other-class-a {
}
此外,当欲通过部分类名我匹配可以使用
[class^="my-class-"] {
}
现在我想混合两者,但它似乎并没有工作。我该怎么办
[class^="my-class-"].my-other-class-a {
}
这不完全防弹的,但只要你的“变量”级是第一位的,这可以工作:
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>
出现这种情况因为class属性是从css选择器[class^="abc"]
中的指定类开始测试的。
如果选择是
[class^="my-"]
然后
class="my-class red"
是不一样的
class="red my-class"
瞧瞧吧http://jsfiddle.net/u5sfge94/
一种方法解决此我s来指定一个充当[class^=“abc”]的新类。它可能会让你的样式表更加有组织,你的代码更清晰,并且CSS会更快地呈现出来。
在之前的回答中@juank的解释是正确的:您写下类的顺序很重要,因为^代表价值的开始。
但也有使用正则表达式许多其他的属性选择符号:^=
,*=
,特别$=
; RESP。从任何地方开始,并以匹配结束。
如果您希望您的选择器与包含my-class
的类匹配,则应使用*=
(请参阅片段1)。
但是,它也会匹配任何不以my-class
开头的类,但仍包含它。为避免这种情况,您可以像以前一样匹配^=
,也可以匹配[class*=" my-class"]
(带空格):它将考虑它不是第一类写入类属性值的情况(请参阅摘录2)。
资源:CSS3 Substring Matching Attribute Selectors at CSS3。信息(链接到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>