如果存在2个元素,则应用CSS [英] CSS to apply if 2 elements exist

查看:71
本文介绍了如果存在2个元素,则应用CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下HTML标记,我只想在存在 2 个相同元素时才应用(S)CSS(而不是在存在1个元素时).

Given the following HTML markup, I want to apply (S)CSS only when 2 of the same elements exist (not when 1 exists).

我不想使用JavaScript来计算元素数量并应用另一个类,但是,我认为这是唯一的方法.

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>

推荐答案

您可以使用数量查询".对于恰好两个...

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 {

}

来源: 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个元素,则应用CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆