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

问题描述:

我已经建立了我的UL的最后一个LI标签的规则:选择最后一个孩子,除非它也是第一个孩子

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

我是否能够设置在说CSS规则“应用此样式到最后的LI标签,除了last-child也是first-child“,即在OL中只有一个LI标签。

可以连同: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>

+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选择正在修改。

+0

唯一的事情就是我别如果它只是一个独生子女,就不得不设置另一种风格。我想说“如果UL中有多个LI,只应用这种风格”。 –

你可以留下你的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 - 第一个子
+0

接下来的问题是我不得不通过定义第一个孩子来为LI设置样式。 –

+0

看看我的编辑。 –

您可以像li:last-child一种化合物选择之前预先准备* +以防止它选择的第一个孩子:

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