css - nth-child 或 first/last-child 选择器不起作用。如何正确应用它们?

标签 css css-selectors

我有一个结构:

<div id="div">
    <ul class="ul">
        <li class="li_one">
        </li>
        <li class="li_two">
        </li>
    </ul>
</div>

我想使用伪选择器将 background:red 设置为第二个 li 元素(类“li_two”),并希望从最外层的 div 开始。我正在尝试这样:

#div > ul:nth-child(1) { background:red; }   // works but wrong, sets background to ul
#div ul:last-child { background:red; }   // doesn't set to any element
#div ul:first-child { background:red; }  // again sets to ul but not to li
#div [class=li_two] { background:red; }  // only this one works fine

是否可以使用 :nth-child:last-child#div 将样式设置为 li_two code> 或 :first-child 选择器?怎么做?

最佳答案

#div li:last-child

您的第二个选项几乎是正确的 :) 我认为您误解了 last-child 的作用。 xx:last-child 不选择元素xx的最后一个子元素;它选择作为其父项的最后一个子项的每个 xx 元素。

Some reading .

I've created a JSFiddle for you to test it

关于css - nth-child 或 first/last-child 选择器不起作用。如何正确应用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647925/

相关文章:

jquery - 在 jQuery 中使用第 n 个子选择器是否依赖于浏览器对 CSS3 的支持?

css - 原生 CSS 嵌套困惑

html - 证明在 100% 宽度 div 中对齐 tagcloud?

css - 有没有办法建议如何在 HTML5 中打印页面?

javascript - 如何使用 DOM 方法在不同位置创建多个元素

css - 哪些字符在 CSS 类名/选择器中有效?

css - 背景:透明;与背景:0 0;差异和威胁

css - Safari 6 渐变颜色混合/插值错误

html - 使用 CSS 选择器遍历 HTML 标签树

javascript - <select>...</select> 源代码的 CSS 选择器