给定下面的HTML标记,我只想在存在2个相同元素时(而不是在存在1个元素时)应用(多个)CSS。
我不想使用JavaScript来统计元素的数量并应用另一个类,然而,我感觉这是唯一的方法。
div {
a + a {
// I want to apply styles to both a tags, not just the second one
// WHEN 2 a tags exists
}
}
<div>
<a href="/">Home</a>
<a href="/about">About</a>
</a>
您可以使用“数量查询”。 正好两个。。。
a:nth-last-child(n+2):nth-last-child(-n+2):first-child,
a:nth-last-child(n+2):nth-last-child(-n+2):first-child ~ a {
}
图片来源:https://quantityqueries.com/
null
a:nth-last-child(n+2):nth-last-child(-n+2):first-child,
a:nth-last-child(n+2):nth-last-child(-n+2):first-child~a {
color: red
}
<div>
<a href="/">Home</a>
<a href="/about">About</a>
</div>
<div>
<a href="/">Home</a>
</div>
<div>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/more">More</a>
</div>
update:初始问题说明“存在2个或更多相同元素”,但后来更新了...
你可以像下面这样做:
null
a:first-child:nth-last-child(n + 2),
a ~ *{
color:red;
}
<div>
<a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
<a href="/">Home</a> <a href="/about">About</a> <a href="/">Home</a> <a href="/about">About</a>
</div>
<div>
<a href="/">Home</a>
</div>
请尝试使用:div a:nth-child(n+2){}
(n+2)是选择除前2个以外的全部。
你可以查看这个链接,也许它会帮助你。
https://css-tricks.com/wified-nth-child-recipies/