html - 类选择器和类以选择器开头

标签 html css css-selectors

我想将像 .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/

相关文章:

jquery - 加载时显示页面移动版本的图像

javascript - 自动滚动到可滚动 div 中的元素

javascript - 元素符号列表不显示在所选容器中

html - 来自 float div 的 CSS 填充

css - 伪选择第 n 个 child 问题

html - 仅使用CSS定位按钮之一

javascript - 按下按钮时删除父 div

html - 在 Bootstrap 中更改事件类 CSS

html - @Font-Face 跨浏览器兼容性问题

css - 如何使用 css 定位所有其他 iframe?