css - 在多个 parent 中选择第 n 个 child

标签 css parent-child css-selectors

我有以下标记:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
    </ul>
    <ul>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

我想设置“一”和“三”的样式。

但是,标记也可以是:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

我试过使用以下 CSS:

.foo li:nth-child(1),
.foo li:nth-child(3)
{
    color:red;
}

但是,正如预期的那样,这是为每个 ul 的第一个子元素设置样式。 (演示:http://jsfiddle.net/hTfVu/)

如何更改我的 CSS 以便我可以定位属于 .foo 的第一个和第三个 li

最佳答案

单靠 CSS 选择器无法做到这一点。 :nth-child() 和 sibling 组合器仅限于共享同一父级的子级/兄弟级,正如它们的名字所暗示的那样,CSS 选择器无法解释父子结构中的这种变化,也不是有任何类似 :nth-grandchild() 选择器的东西(甚至 :nth-match() from Selectors 4 将自身限制为仅共享同一父元素的元素)。

当然,对于像 jQuery 这样的东西,它变得微不足道:$('.foo li:eq(0), .foo li:eq(2)') 否则你必须标记第一个和第三个 li 元素明确使用类或 ID,然后选择它们。

关于css - 在多个 parent 中选择第 n 个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52452240/

相关文章:

html - 将我的样式表与 HTML 文件集成时遇到问题

html - 如何在 child 上课前应用css

html - 带有多行文本的标签内的中心复选框

twitter-bootstrap - :before pseudo-element when there is one class but NOT another class 的 CSS 选择器

html - 选择最后一个连续的 sibling

html - CSS div 和 :hover positions

html - CSS GRID - 具有空单元格和自动放置的网格模板区域

javascript - 如何为 float div 的重新洗牌设置动画?

parent-child - 子元素 bg 颜色剪辑到父 border-radius

java - 创建一个子 Activity 以从列表中选择数据