所以我能够detect the number of siblings an element has by using nth-child(),但是我还没有找到根据兄弟姐妹总数选择最后几个元素的方法。
在下面的代码片段中,我通过添加类实现了我想要的目标。但是如果可能的话,我想用一种方法来实现这一点,只需使用CSS选择器。在以下代码段中,每个"组"有2行,一行被定义为3个元素。我想在下面的代码段中选择橙色元素而不添加类。选择最后一行中的元素或选择除最后一行之外的所有元素。
ul {
padding-left: 0;
}
ul::after {
content: '';
display: table;
clear: both;
}
li {
background-color: #efefef;
border: 1px dotted #000;
box-sizing: content-box;
float: left;
list-style-type: none;
padding: 10px 0;
text-align: center;
width: 33%
}
.alt {
background-color: orange;
}

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="alt">4</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="alt">4</li>
<li class="alt">5</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="alt">4</li>
<li class="alt">5</li>
<li class="alt">6</li>
</ul>
&#13;
答案 0 :(得分:2)
由于nth-last-child
可以采用公式,因此您可以使用与您引用的其他问题相同的技术为任意数量的元素执行此操作。
ul {
padding-left: 0;
}
ul::after {
content: '';
display: table;
clear: both;
}
li {
background-color: #efefef;
border: 1px dotted #000;
box-sizing: content-box;
float: left;
list-style-type: none;
padding: 10px 0;
text-align: center;
width: 33%
}
/* 3 elements in last row */
li:first-child:nth-last-child(3n+0) ~ li:nth-last-child(1),
li:first-child:nth-last-child(3n+0) ~ li:nth-last-child(2),
li:first-child:nth-last-child(3n+0) ~ li:nth-last-child(3),
/* 2 elements in last row */
li:first-child:nth-last-child(3n+2) ~ li:nth-last-child(1),
li:first-child:nth-last-child(3n+2) ~ li:nth-last-child(2),
/* 1 element in last row */
li:first-child:nth-last-child(3n+1) ~ li:nth-last-child(1) {
background-color: orange;
}
&#13;
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
</ul>
&#13;
表达式li:first-child:nth-last-child(3)
需要一个li
,它是其父的first-child
和,也是最后一个孩子的第三个li:first-child:nth-last-child(3n+0)
。这两个约束一起意味着父元素必须正好有3个子元素。以类似的方式,~
表示父母必须拥有多个3的子女。
一旦我们约束了第一个元素的有效性,我们就需要选择最后一个元素以突出它们。兄弟选择器(nth-last-child
)将选择匹配元素的兄弟节点,我们再次使用.row:last-child div.article-container{
background-color: white;
}
从末尾选择元素N.
这些规则被组合并重复以处理最后一行中的1,2或3个元素的情况。