我想将像 .smart
这样的类选择器与 [attr^=val]
选择器结合起来,它的 attr
是一个 类
,如[class^='test-']
。我已经单独测试了每个选择器,它们似乎工作得很好。然而,当结合使用时,它们无法产生预期的结果。
例子
您也可以view the Codepen .
/* Works */
[class^='test-'] {
background: blue;
}
/* Works */
.smart {
background: yellow;
}
/* Doesn't work */
[class^='test-'].smart {
background: red;
}
<div class="test-me">
<p>Should be blue.</p>
</div>
<div class="smart">
<p>Should be yellow.</p>
</div>
<div class="smart test-me">
<p>Should have been red, but isn't.</p>
</div>
谁能解释为什么 CSS 选择器 [class^='test-'].smart
不起作用,如果可能的话,如何解决这个问题?
最佳答案
why the CSS selector
[class^='test-'].smart
does not work
因为你的class属性不是以test-
开头的。它以 smart
开头。如果它确实以test-
开头,像这样:
<div class="test-me smart">
<p>Should be red.</p>
</div>
然后它会匹配。
how to fix the problem
当属性不以test-
开头时,您需要一个额外的选择器。如所述here :
[class^='test-'].smart, [class*=' test-'].smart {
background: red;
}
<div class="smart test-me">
<p>Should be red.</p>
</div>
<div class="test-me smart">
<p>Should also be red.</p>
</div>
关于html - 类选择器和类以选择器开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510359/