Select nth-child across multiple parents(在多个父母中选择第 n 个孩子)
问题描述
我有以下标记:
<div class="foo">
<ul>
<li>one</li>
<li>two</li>
</ul>
<ul>
<li>three</li>
</ul>
<ul>
<li>four</li>
</ul>
</div>
我希望设置一"和三"的样式.
I wish to style "one" and "three".
但是,标记也可以是:
<div class="foo">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<ul>
<li>four</li>
</ul>
</div>
我尝试过使用以下 CSS:
I've tried using the following CSS:
.foo li:nth-child(1),
.foo li:nth-child(3)
{
color:red;
}
但是,正如预期的那样,这是为每个 ul 的第一个子元素设置样式.(演示:http://jsfiddle.net/hTfVu/)
However, as expected, this is styling the first child of each ul. (Demo: http://jsfiddle.net/hTfVu/)
如何更改我的 CSS 以便可以定位属于 .foo 的第一个和第三个 li?
How can I change my CSS so that I can target the 1st and 3rd li belonging to .foo?
推荐答案
你不能单独使用 CSS 选择器.:nth-child() 和兄弟组合器仅限于共享相同父级的子级/兄弟级,正如它们的名称所暗示的那样,CSS 选择器不能解释父子结构中的这种变化,也不能有类似 :nth-grandchild() 选择器(甚至 :nth-match() from Selectors 4 将自身限制为仅共享同一父级的元素.
You can't do that with CSS selectors alone. :nth-child() and sibling combinators are limited to children/siblings sharing the same parent only, as implied by their names, and CSS selectors cannot account for such variations in parent-child structure, nor is there anything like an :nth-grandchild() selector (even :nth-match() from Selectors 4 limits itself to elements sharing the same parent only).
当然,对于像 jQuery 这样的东西,它变得微不足道:$('.foo li:eq(0), .foo li:eq(2)') 否则你必须标记第一个和第三个 li 元素显式使用类或 ID,然后选择它们.
Of course with something like jQuery it becomes trivial: $('.foo li:eq(0), .foo li:eq(2)') Otherwise you'll have to mark the first and third li elements explicitly using classes or IDs, and then select them.
这篇关于在多个父母中选择第 n 个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在多个父母中选择第 n 个孩子
基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
