14

以下面的代码为例:

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

是否有可能,使用:nth-child()或以其他方式,准确选择总元素的一半?在上面的例子中,代码应该选择第一个/最后两个 ,然后如果我将s 的数量增加到六个,它将选择第一个/最后三个lili

我觉得我将不得不使用 JavaScript ......

4

3 回答 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个项目;:nth-child(n+3)将选择除前3 个项目之外的所有项目。将它们组合起来,您可以根据元素后面的内容(或父项中有多少子项)在纯 CSS 中选择元素。如果您希望此技巧适用于 150 个元素,则必须将其中的 75 个与 74 个逗号组合在一起... :)

兼容性为 IE9+(存在 JS polyfills)

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

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

于 2013-03-17T23:52:45.943 回答
5

在纯 CSS 中,你能够接近nth-child(odd)它的唯一方法是在or上做一个选择器nth-child(even)。如果您想要准确的后半部分(而不是奇数或偶数),那么您必须使用 JavaScript/jQuery。

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

var yourList = $("ul li");

yourList = yourList.slice(0, Math.floor(yourList.length/2));
于 2013-03-17T22:19:11.073 回答
2

例子

为这些元素创建一个带有样式的 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. 在示例中可以看到所有可能性。

于 2013-03-17T22:22:41.137 回答