我将第三方CSS(不允许修改)导入了我的应用程序。该CSS文件声明了一个类名和一个选择器,例如:
.third-party-class{
color: blue;
}
.third-party-class:last-of-type{
color: red;
}
我的目标是仅使用CSS完全删除.third-party-class:last-of-type
选择器。当然,您可以覆盖.third-party-class:last-of-type
选择器并复制.third-party-class
中的每个属性。但是,如果.third-party-class
具有很多属性,这确实很不方便。
.third-party-class{
color: blue;
}
.third-party-class:last-of-type{
color: red;
}
.desired-li{
color: blue;
}
<div>
Currently:
<ul>
<li class="third-party-class">one</li>
<li class="third-party-class">two</li>
<li class="third-party-class">three</li>
</ul>
Desired:
<ul>
<li class="desired-li">one</li>
<li class="desired-li">two</li>
<li class="desired-li">three</li>
</ul>
</div>
问题
是否可以完全重写/删除CSS选择器,而不必仅通过使用CSS(无JS)来重新声明“基本”类的所有属性?
答案 0 :(得分:1)
由于我们正在处理last-of-type
,并且您无法更改CSS,因此可以添加一个额外的元素来触发该选择器并将其隐藏(我想您可以调整HTML):
.third-party-class {
color: blue;
}
.third-party-class:last-of-type {
color: red;
background:pink;
font-size:250px;
opacity:0.9;
display:flex;
vertical-align:sub;
/*doesn't matter what CSS you will have here*/
}
ul li:last-of-type {
display:none!important;
}
<ul>
<li class="third-party-class">one</li>
<li class="third-party-class">two</li>
<li class="third-party-class">three</li>
<li></li>
</ul>
答案 1 :(得分:0)
我同意BenM对您的原始问题的评论。
但是...如果CSS像您的小提琴一样简单(只有一行),使我相信您可以在要覆盖的选择器上使用“!important”。
.third-party-class:last-of-type{
color: blue !important;
}
这将允许您在逐个选择器的基础上(假设使用的不仅仅是颜色),指定您希望第三方代码执行的操作。
答案 2 :(得分:0)
您可以使用[attribute^=value]
选择器,它将覆盖以“值”开头的所有元素,因此您可以进行以下操作:
.third-party-class{
background: blue;
height: 20px;
width: 20px;
margin-bottom: 10px;
}
.third-party-class:last-of-type{
background: red;
}
div[class^="third-party-class"]{
background: green;
}
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
<div class="third-party-class"></div>
对不起,如果我听不懂