CSS选择另一个元素的多个后代

时间:2012-06-15 16:00:18

标签: css css-selectors

是否可以在CSS中选择具有某个类,id等祖先的多个元素? e.g:

table.exams caption, tbody, tfoot, thead, tr, th, td

如果没有,有没有办法选择该元素的所有后代?

4 个答案:

答案 0 :(得分:26)

  

是否可以在CSS中选择具有某个类,id等祖先的多个元素?

目前,不是没有重复整个祖先选择器并指定所有后代,遗憾的是 1

table.exams caption, 
table.exams tbody, 
table.exams tfoot, 
table.exams thead, 
table.exams tr, 
table.exams th, 
table.exams td

只有在Selectors 3最终确定之后,他们才提出了一个伪类符号来实现这一点,并且直到最近基本实现才开始出现。有关历史课程,请参阅this answer

简而言之,现在进入标准的伪类被称为:matches()。在遥远的未来,一旦浏览器开始实施:matches(),您就可以做到这样的事情:

table.exams :matches(caption, tbody, tfoot, thead, tr, th, td)
  

如果没有,有没有办法选择该类的所有后代?

嗯,您只需使用代表any element的星号*即可。鉴于您的选择器中有thtd,您可能意味着所有后代而不是table.exams的所有子项,因此请勿使用>,请使用空格代替:

table.exams *

但实际上,避免这样做。如果可以,请尽最大努力指定您尝试选择的后代。


1 特别是对于表格,您可以使用table.exams > :not(.colgroup), table.exams > * > tr > *,但正如您所知道的那样令人难以置信的神秘(更不用说假设您没有script-supporting elements这个表中的嵌套表,你最好只列出你想要的所有后代。

答案 1 :(得分:1)

您现在可以使用 :is() 选择器执行此操作。如果它需要更大的选择,您可以使用 :not 与它的组合来排除较小的比率,如代码段所示:

此选择器可用于所有 4 种主要浏览器(Edge、Firefox、Chrome 和 Safari)的最新版本:https://caniuse.com/?search=is 自 2021 年 1 月 26 日起。

.match-elements :is(.match-1,.match-2,.match-5,.match-10) {
  background: #5548B0;
}

.match-elements :not(:is(.match-1,.match-2,.match-5,.match-10)) {
  background: #BADA55;
}

/* For snippet styling, not required */

.match-elements div {
  font-family: sans-serif;
  font-weight: 600;
  color: white;
  padding: 10px;
  margin: 10px 0;
}
<div class="match-elements">
  <div class="match-1">Matched using is</div>
  <div class="match-2">Matched using is</div>
  <div class="match-3">Matched using not</div>
  <div class="match-4">Matched using not</div>
  <div class="match-5">Matched using is</div>
  <div class="match-6">Matched using not</div>
  <div class="match-7">Matched using not</div>
  <div class="match-8">Matched using not</div>
  <div class="match-9">Matched using not</div>
  <div class="match-10">Matched using is</div>
</div>

答案 2 :(得分:0)

子选择器如下所示:

ul > li {

}

这将定位li

的所有ul直接子项

如果您想定位所有后代,请使用*选择器

我不确定我是否已理解你问题的第一部分了!

答案 3 :(得分:0)

  

是否可以在CSS中选择具有某个类的祖先的多个标签?

可以使用SCSS获得类似于:matches的结果,如this article

所示

此外,某些浏览器部分支持具有供应商特定前缀的:matches