如果存在 2 个元素则应用 CSS

ste*_*web 1 html css css-selectors

给定以下 HTML 标记,我只想仅在存在2个相同元素时(而不是存在 1 个时)应用 (S)CSS 。

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

div {
  a + a {
    // I want to apply styles to both a tags, not just the second one
    // WHEN 2 a tags exists
  } 
}
Run Code Online (Sandbox Code Playgroud)
div {
  a + a {
    // I want to apply styles to both a tags, not just the second one
    // WHEN 2 a tags exists
  } 
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*e_D 6

您可以使用“数量查询”。正好两个...

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 {

}
Run Code Online (Sandbox Code Playgroud)

来源: 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 {

}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)