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 个孩子


- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01