问题
Given the following HTML markup, I want to apply (S)CSS only when 2 of the same elements exist (not when 1 exists).
I don't want to use JavaScript to count the number of elements and apply another class, however, I feel this is the only approach.
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>
回答1:
You can use "quantity queries". For exactly TWO...
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 {
}
Source: https://quantityqueries.com/
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>
回答2:
UPDATE: the initial question stated "2 or more of the same elements exist" but was updated later ...
You can do it like below:
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>
Or like below too:
a:not(:only-child){
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>
回答3:
are you using pre-compilor? then
div a:nth-child(n+2) {
background: red
}
<div>
<a href="/">Home</a>
<a href="/about">About</a>
</a>
For Scss, following code should work
div {
& a:nth-child(n+2) {
// css instruction
}
}
来源:https://stackoverflow.com/questions/62469473/css-to-apply-if-2-elements-exist