使用 :nth-child 选择一半元素?

问题描述 投票:0回答:3

以下面的代码为例:

<ul>
  <li>Hello World</li>
  <li>Hello World</li>
  <li>Hello World</li>
  <li>Hello World</li>
</ul>

是否可以使用

:nth-child()
或其他方式精确选择全部元素的 half?代码应该在上面的实例中选择第一个/最后一个 two
li
,那么如果我将
li
的数量增加到六个,它将选择第一个/最后一个 Three

我觉得我必须使用 JavaScript...

html css css-selectors
3个回答
17
投票

您可以选择纯CSS中的一半元素......在一定程度上。
唯一的缺点是您必须知道总项目的最大数量。可能是 150,但它不适用于 151。

这是一个演示:http://jsfiddle.net/tcK3F/ (*)

最小 CSS:

/* selecting half or more items. Up to 6 */
li:first-child:last-child,
li:nth-child(n+2):nth-last-child(-n+2),
li:nth-child(n+3):nth-last-child(-n+3),
li:nth-child(n+4):nth-last-child(-n+4),
li:nth-child(n+5):nth-last-child(-n+5),
li:nth-child(n+6):nth-last-child(-n+6) {
  color: white;
  background: darkblue;
}

/* selecting half or less items. Up to 6 */
li:nth-child(n+2):last-child,
li:nth-child(n+3):nth-last-child(-n+2),
li:nth-child(n+4):nth-last-child(-n+3),
li:nth-child(n+5):nth-last-child(-n+4),
li:nth-child(n+6):nth-last-child(-n+5),
li:nth-child(n+7):nth-last-child(-n+6){
  font-style: italic;
  border: 2px solid red;
}

基于以下想法:
这个技巧来自 André Luís,并在 Lea Verou 的一篇文章中看到:基于兄弟计数的样式元素。我根据您的拆分选择需求进行了调整。

快速解释:

:nth-last-child(-n+3)
将从父级中选择 3 个 last 项目;
:nth-child(n+3)
将选择所有项目 除了前 3 个项目。将它们结合起来,您就可以根据它们后面的内容(或者父级中有多少个子级)来选择纯 CSS 中的元素。除非你想要这个技巧适用于 150 个元素,否则你必须将其中的 75 个与 74 个逗号组合起来......:)

兼容性为 IE9+(存在 JS 填充)

(*)
HTML 代码的第一部分:偶数列表项;
第二部分:奇数个列表项

第一个 CSS 规则:将从 2N 个项目中选择最后 N 个项目或从 2N+1 个项目中选择最后 N+1/2 个项目,并将它们设置为蓝底白字(例如:总共 5 或 6 个项目中的 3 个项目)。
第二个 CSS 规则:将从 2N 个项目中选择最后 N 个项目或从 2N+1 个项目中选择最后 N-1/2 个项目,并使用红色边框和斜体设置它们的样式(例如:总共 4 或 5 个项目中的 2 个项目)


6
投票

想要在纯 CSS 中实现接近的唯一方法是在

nth-child(odd)
nth-child(even)
上执行选择器。如果你想要精确的后半部分(而不是奇数或偶数),那么你必须使用 JavaScript/jQuery。

使用 jQuery,你可以使用以下方法获取它们:

var yourList = $("ul li");

yourList = yourList.slice(0, Math.floor(yourList.length/2));

3
投票

示例

为这些元素创建一个具有样式的 CSS 类:

.half {
    background-color: #18D;
}

然后,使用 jQuery 将该类添加到指定的元素集中:

$(function () {
  var $lis = $('ul li')
  var length = $lis.length

  // Add class to first half:
  $lis.slice(0, Math.floor(length / 2)).addClass('first')

  // Add class to last half:
  $lis.slice(length - Math.floor(length / 2)).addClass('first')
})

如果您确实想在元素数量为奇数的情况下包括中间的元素,请将

Math.floor
更改为
Math.ceil
。所有可能性都可以在示例中看到。

© www.soinside.com 2019 - 2024. All rights reserved.