html - 第 n 个元素的 CSS 选择器,与父元素无关

标签 html css css-selectors

<分区>

是否有第 n 个匹配元素的 CSS 选择器,而不管任何父元素。

例如下面如何选择刚才的“第二段”。没有第四个吗?

<div>
   <p>The first paragraph.</p>
   <p>The second paragraph.</p>
</div>

<div>
   <p>The third paragraph.</p>
   <p>The fourth paragraph.</p>
</div>

我认为 p:nth-oftype(2) 会这样做,但它同时选择了第二个和第四个(这是每个父 div 的第二个)。

JSFiddle - https://jsfiddle.net/km4nbfz9/

编辑 - 这只是 HTML 的一个示例位,问题是如何使它适用于匹配 CSS 选择器的第 n 个元素,而不管父元素和结构如何。

最佳答案

没有

spec说:

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.

没有 nth-of-DOM 选择器。

这里的关键字是 sibling ..这需要 parent ,而不是叔叔或祖 parent 等。

@Marcos Pérez Gude 的评论中所述

“DOM 是一棵树。因此,如果您考虑一下,一个节点总是依赖于它的父节点。”

关于html - 第 n 个元素的 CSS 选择器,与父元素无关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657979/

相关文章:

jquery - CSS3/jQuery 选择器通过 :nt-child() selector 设置 2 行组的样式

java - 无法通过 Selenium 和 WebDriver 定位元素

html - 如何垂直居中 Bootstrap 列元素

html - 使父宽度小于子宽度

css - Zurb 基金会 : compile Sass with my own overrides (e. g。始终设置表格宽度 100%)

javascript - 有没有办法使用查询选择器选择具有一些文本数据的第一个 p 标签

html - 将鼠标悬停在上面的图像上时,如何更改 slider 的不透明度?

html - iframe 在父级内部的高度为零,没有高度和底部填充

javascript - 谷歌地图信息窗口滚动错误 : How to solve for all cases?

html - 减小模式窗口大小以适应修改 CSS 的表单字段