<分区>
<分区>
如何使用 CSS 查找给定类型的第一个元素?
我在尝试:
a:first-of-type { }
和
a:nth-of-type(1) { }
但他们也在选择子元素。我只需要选择第一个 <a>
在整个页面中标记。
最佳答案
一般情况在 CSS 中是不可能做到的。只有 JS/jQuery 允许它或精确了解给定页面中的 HTML 结构。
为什么?
元素无法知道在其祖先之一的前一个兄弟中是否存在“前一个”a
元素。因为没有也不会有父选择器。
<body>
<p>
<a href="#"><!-- the one you'd want to select -->
</p>
<a href="#"><!-- this one knows he is the first of his type in the pool of direct descendant (children) of body
but no more can be achieved (in CSS) -->
</body>
在纯 CSS 中,您可以为给定级别选择其各自父元素的每种第一类型元素,例如:
body > * > * > a:first-of-type { /* level 3, great-grandchildren of body */ }
这几乎是所有的总结
关于html - CSS 选择类型的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31109545/