css - 如何在不依赖父选择器或使用 !important 的情况下添加 CSS 特异性?

标签 css css-specificity

<分区>

blue 应该是蓝色而不向元素添加 id,不使用 JavaScript 并且不知道父级 #id,因为它们可以在未来的某个日期更改,同时允许用于设置正确应用的样式属性的 JavaScript。

custom-tag {
  color: blue; 
  /* 
   * the above should have the specificity of exactly 2×ids + 1×tag
   */
}


/*  later loaded CSS, which is not controllable... */

#one custom-tag, #two custom-tag {
  color: red;
}
<div id="one">
  <custom-tag>blue</custom-tag>
  <custom-tag style="color:orange">orange</custom-tag>
</div>

<div id="two">
  <custom-tag style="color:green">green</custom-tag>
  <custom-tag>blue</custom-tag>
</div>

最佳答案

在不需要 parent 的情况下增加选择器的特异性,使用 :not() + 具有所需特异性的不存在的选择器:

any-tag:not(#bogus_id):not(#bogus_id) {
  color: blue; 
}

#one any-tag, #two any-tag  {
  color: red;
}
<div id="one">
  <any-tag>blue</any-tag>
  <any-tag style="color:orange">orange</any-tag>
</div>

<div id="two">
  <any-tag style="color:green">green</any-tag>
  <any-tag>blue</any-tag>
</div>

关于css - 如何在不依赖父选择器或使用 !important 的情况下添加 CSS 特异性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410231/

上一篇:javascript - DIV 突然出现而不是 slideDown() 方法发生

下一篇:html - 我需要放置4张背景图片,然后悬停时图片会改变它的位置

相关文章:

html - 如何在 SVG 中绘制垂直线

html - 子导航栏下拉菜单不起作用

html - 如何防止 HTML 元素成为 CSS 规则的目标?

CSS 特异性问题 - 为什么这个选择器优先?

html - 为部分页面中的特定标签设置默认字体样式

css - Hexo 'alt text' 不工作

html - 如何为 ionic slider 元素符号提供边框颜色

html - 如何使用一个 anchor 标签打开多个标签页?

ID 内的 CSS 类胜出

css - 在一个元素中使用多个类和特异性