html - CSS 选择类型的第一个元素

标签 html css css-selectors element

<分区>

如何使用 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/

上一篇:jquery - 同位素自动高度修复

下一篇:javascript - 平滑的鼠标滚轮滚动

相关文章:

javascript - 奇怪的 CSS 显示问题

html - 为什么垂直对齐 : middle causes other elements to misalign?

javascript - 避免可拖动对象一旦掉落就变成 "droppable areas"

html - 为什么这个 div 不是居中的?我不明白

css - 如何使文本不响应?

css - 由 ID 选择的链接中的文本颜色覆盖了不同 ID 的父链接颜色

css - Flexbox children 并不总是扩展到他们可以/应该的那么宽

css - bootstrap3 tabindex 更改我的 css 样式

html - 在数据切换上显示正确的雪佛龙 - 仅限 css

html - CSS 选择器特异性和文件加载顺序