选择最后一个孩子,除非它也是第一个孩子

时间:2016-07-07 23:34:24

标签: css css-selectors

我已经为我的UL的最后一个LI标签设置了规则:

.className li:last-child {
  stuff: here;
}

我能否在CSS中设置一条规则,即“将此样式应用于最后一个LI标记,除非last-child也是first-child”,即只有一个LI标记OL。

4 个答案:

答案 0 :(得分:4)

您可以将其与:not()选择器一起使用。

  

CSS伪类:not(X)是一个功能符号,它将一个简单的选择器 X 作为参数。它匹配一个未由参数表示的元素。

li:last-child:not(:first-child) {
  color: red;
}
<ul>
  <li>item a</li>
  <li>item b</li>
  <li>item c</li>
</ul>

<ul>
  <li>only item</li>
</ul>

答案 1 :(得分:2)

您可以保留CSS原样并添加一条规则,如果它是第一个孩子,则覆盖它:

/* What should happen in the last child */
.className li:last-child {
    stuff: here;
}

/* If there is only one child the previous one will be overwritten by this one */
.className li:first-child {
    /* default values */
}

或者,您可以使用更高级的东西:

/* Select the last child if it is not the first child */
li:last-child:not(:first-child) {
    stuff: here;
}

我会使用第二种,但这取决于你对CSS的熟悉程度。

更具分析性

  • :last-child - 选择最后一个孩子
  • :not() - 如果不是
  • :first-child - 第一个孩子

答案 2 :(得分:1)

您可以在* +之类的复合选择器之前添加li:last-child,以防止它选择第一个孩子:

&#13;
&#13;
.className > * + li:last-child {
  color: red;
}
&#13;
<ul class="className">
  <li>item a</li>
  <li>item b</li>
  <li>item c</li>
</ul>
<ul class="className">
  <li>only item</li>
</ul>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

有一个:only-child选择器:

https://css-tricks.com/almanac/selectors/o/only-child/

以及:only-of-type选择器

https://css-tricks.com/almanac/selectors/o/only-of-type/

您可以使用这些来覆盖:last-child选择器正在修改的任何内容。

相关问题