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

问题描述 投票:0回答:2

这个问题在这里已有答案:

blue应该是蓝色而不添加id到元素,不使用JavaScript而不知道父#ids,因为它们可以在将来更改,同时允许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>
css css-specificity
2个回答
2
投票

使用: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>

0
投票

您还可以像这样叠加选择器:

.selector.selector

这会增加特异性。

你也可以堆叠它们两次以上。

适用于所有浏览器。

© www.soinside.com 2019 - 2024. All rights reserved.