Reputation: 16551
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>
Upvotes: 1
Views: 3523
Reputation: 273077
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>
Upvotes: 3
Reputation: 304
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
}
}
Upvotes: -3
Reputation: 115136
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>
Upvotes: 6