html - 为什么我的第一个子选择器不能处理具有指定类的选择中的第一个元素?

标签 html css css-selectors pseudo-class

对于 first-child 的正确使用,我有点一窍不通。

我有一个(动态生成的)元素,最终将包括:

<h1>
  <a>Foo</a>
  <a.trigger>Trigger A</a>
  <a.trigger>Trigger B</a>
  <span.bar>Bar</span>
</h1>

我需要为 trigger 链接设置样式。这就是我正在做的:

.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a.trigger {
  background: none repeat scroll 0 0 transparent;
  border: 0 none;
  border-radius: 0;
  box-shadow: none;
  position: absolute;
  right: 2em;
  height: 100%;
  top: 0;
  width: 2em;
}
.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a.trigger:first-child {
  right: 0;
  background-color: red !important;
  border-right: 1px solid red;
}

我已经尝试了 a.trigger:first-childa.trigger:nth-of-type(1) 但我无法覆盖CSS 由第一条规则设置。两个选择器也具有相同的特异性,所以这不是原因。

问题:
我想我错过了一些明显的东西......也许有人可以帮助我。谢谢!

最佳答案

:first-child 匹配其父项的第一个子项。你的第一个 a.trigger 不是第一个 child ——那将是它之前的无类 a

:first-of-type:nth-of-type(1) 是等价的,匹配其父元素中其类型的第一个元素。在这种情况下,您的无类 a 也是其父级的第一个 a,使您的第一个 a.trigger 成为第二个 a 元素。

您给定的结构是否始终会生成您的动态元素?如果是这样,您只需选择 a.trigger:nth-child(2) 而不是 a.trigger:first-child:

.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a.trigger:nth-child(2) {
  right: 0;
  background-color: red !important;
  border-right: 1px solid red;
}

或者你可以尝试a + a.trigger:

.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a + a.trigger {
  right: 0;
  background-color: red !important;
  border-right: 1px solid red;
}

(顺便说一句,可能不需要 !important。)

否则,如果您需要选择第一个 a.trigger,通常您需要对您的声明进行不同的排序并稍微更改您的选择器:

.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a.trigger {
  background: none repeat scroll 0 0 transparent;
  background-color: red !important;
  border: 0 none;
  border-right: 1px solid red;
  border-radius: 0;
  box-shadow: none;
  position: absolute;
  right: 0;
  height: 100%;
  top: 0;
  width: 2em;
}
.ui-collapsible-tabs.ui-dynamic-tabs .ui-collapsible-heading a.trigger + a.trigger {
  right: 2em;
  background-color: transparent;
  border-right: 0 none;
}

如果您的两个 a.trigger 并不总是相邻的,请将 + 替换为 ~

详细介绍了通用解决方案 here .

关于html - 为什么我的第一个子选择器不能处理具有指定类的选择中的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18577994/

相关文章:

css - 无法通过第 nth-child 定位其他元素内的元素

python - StaleElementReferenceException:消息:过时的元素引用:使用 Selenium 和 Python 时,元素未附加到页面文档错误

jquery - 带有 mousemove 的交互式背景 mask (jQuery、CSS)

html - 如何让 div 填满整个屏幕(Masonry/Pinterest)布局

php - 根据分隔符切片 HTML

javascript - 检查元素是否存在并开始一些事件

html - div 右上角的位置图标

php - 简单的HTML DOM-(直接)子选择器

html - 在 Open Graph 标记中,没有位置 (href) 的 'og:locale:alternate' 有什么用?

javascript - Modal 中的 iFrame 链接 - 切换 iFrame(保持相同的模式)+++