dan*_*pen 18 css css-selectors
是否有可能在CSS中选择具有某个类,id等祖先的多个元素?例如:
table.exams caption, tbody, tfoot, thead, tr, th, td
Run Code Online (Sandbox Code Playgroud)
如果没有,有没有办法选择该元素的所有后代?
Bol*_*ock 27
是否有可能在CSS中选择具有某个类,id等祖先的多个元素?
目前,不是没有重复整个祖先选择器并指定所有后代,遗憾的是1:
table.exams caption,
table.exams tbody,
table.exams tfoot,
table.exams thead,
table.exams tr,
table.exams th,
table.exams td
Run Code Online (Sandbox Code Playgroud)
只有在Selectors 3最终确定之后,他们才提出了伪类符号才能做到这一点,直到最近基本实现才开始出现.请参阅此答案,了解一点历史课程.
简而言之,现在进入标准的伪类被称为:matches()
.在遥远的未来,一旦浏览器开始实施:matches()
,您将能够做到这样的事情:
table.exams :matches(caption, tbody, tfoot, thead, tr, th, td)
Run Code Online (Sandbox Code Playgroud)
如果没有,有没有办法选择该类的所有后代?
好吧,你可以简单地使用星号*
,它代表任何元素.鉴于你有th
和td
你的选择器,你可能意味着所有后代而不是所有的孩子table.exams
,所以不要使用>
,改为使用空格:
table.exams *
Run Code Online (Sandbox Code Playgroud)
但实际上,避免这样做.如果可以,请尽最大努力指定您尝试选择的后代类型.
1 特别是对于表格,您可以侥幸逃脱table.exams > :not(.colgroup), table.exams > * > tr > *
,但正如您所知道的那样令人难以置信的神秘(更不用说它假设您在此表中没有脚本支持元素或嵌套表格)并且您最好只列出所有你明确想要的后代.
您现在可以使用:is()选择器来执行此操作。如果需要更大的选择,您可以将较小的比例:not
与它组合使用,如代码片段中所示:
此选择器可在所有 4 种主要浏览器(Edge、Firefox、Chrome 和 Safari)的最新版本中使用:https://caniuse.com/?search= is 截至 26/1/2021。
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)