:最后一个孩子不能按预期工作?

问题出在此CSS和HTML之内。这是带有示例代码的jsFiddle的链接。


的HTML


<ul>

    <li class"complete">1</li>

    <li class"complete">2</li>

    <li>3</li>

    <li>4</li>

</ul>

的CSS


li.complete:last-child {

    background-color:yellow;

}


li.complete:last-of-type {

    background-color:yellow;

}

这两行CSS都不应该针对带有“ complete”类的最后一个li元素吗?


jQuery中的此查询也不针对它:


$("li.complete:last-child");

但这确实做到了:


$("li.complete").last();

li {

  background-color: green;

}

li.complete:first-child {

  background-color: white;

}

li.complete:first-of-type {

  background-color: red;

}

li.complete:last-of-type {

  background-color: blue;

}

li.complete:last-child {

  background-color: yellow;

}

<ul>

  <li class="complete">1</li>

  <li class="complete">2</li>

  <li>3</li>

  <li>4</li>

</ul>


忽然笑
浏览 615回答 3
3回答

胡子哥哥

如果该元素不是VERY LAST元素,则:last-child将不起作用除了哈利的答案,我认为添加/强调:如果元素不是容器中的VERY LAST元素,则:last-child将不起作用也至关重要。不管出于什么原因,我花了数小时才意识到这一点,即使Harry的回答很彻底,我也无法从“最后一个孩子选择器用于选择父母的最后一个孩子元素”中提取信息。假设这是我的选择器: a:last-child {}这有效:<div>&nbsp; &nbsp; <a></a>&nbsp; &nbsp; <a>This will be selected</a></div>这不是:<div>&nbsp; &nbsp; <a></a>&nbsp; &nbsp; <a>This will no longer be selected</a>&nbsp; &nbsp; <div>This is now the last child :'( </div></div>这不是因为a元素不是其父元素内的最后一个元素。可能很明显,但这不适合我...

LEATH

我遇到类似的情况。我想让最后一个背景.item变成黄色,看起来像...<div class="container">&nbsp; <div class="item">item 1</div>&nbsp; <div class="item">item 2</div>&nbsp; <div class="item">item 3</div>&nbsp; ...&nbsp; <div class="item">item x</div>&nbsp; <div class="other">I'm here for some reasons</div></div>我nth-last-child(2)用来实现它。.item:nth-last-child(2) {&nbsp; background-color: yellow;}我觉得很奇怪,因为第n个倒数第二个孩子应该是最后一个倒数第二个孩子,但是它可以工作,并且我得到了我期望的结果。我从CSS技巧中发现了这个有用的技巧
打开App,查看更多内容
随时随地看视频慕课网APP