CSS选择另一个元素的多个后代 [英] CSS select multiple descendants of another element

查看:208
本文介绍了CSS选择另一个元素的多个后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在CSS中选择多个具有特定类,id等祖先的元素?例如:

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

如果没有,是否可以选择该元素的所有后代?

解决方案

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

不幸的是, 1 :

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

直到选择器3最终定稿后,他们才提出了伪类标记来实现这一点,直到最近,基本实现才开始出现.参见此答案历史课.

简而言之,现在已经成为标准的伪类称为:matches().在遥远的将来,一旦浏览器开始实现:matches(),您将可以执行以下操作:

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

如果没有,是否可以选择该类别的所有后代?

好吧,您可以简单地使用星号*,它代表任何元素.假设选择器中有thtd,则可能意味着所有后代而不是table.exams的所有子代,因此请不要使用>,而应使用空格:

table.exams *

但实际上,避免这样做.如果可以的话,请尽最大努力指定您要选择的后代类型.


1 特定于表,您可以摆脱table.exams > :not(.colgroup), table.exams > * > tr > *,但是正如您可以说的那样,这是一个难以置信的神秘性(更不用说它假设您没有 解决方案

Is it possible to select multiple elements that have an ancestor of a certain class, id, etc in CSS?

Currently, not without duplicating the entire ancestor selector and specifying all of the descendants, unfortunately1:

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

It was only until late after Selectors 3 was being finalized that they proposed a pseudo-class notation to do this, and it was only recently that basic implementations have started showing up. See this answer for a little history lesson.

In short, the pseudo-class that's now entered the standard is known as :matches(). In the distant future, once browsers start implementing :matches(), you will be able to do something like this:

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

If not, is there a way to select all descendants of that class?

Well, you can simply use an asterisk *, which represents any element. Given that you have th and td in your selector, you probably mean all descendants rather than all children of table.exams, so don't use >, use a space instead:

table.exams *

But really, avoid doing this. If you can, do your utmost to specify what kind of descendants you're trying to select.


1 Specifically with tables, you can get away with table.exams > :not(.colgroup), table.exams > * > tr > *, but as you can tell this is incredibly cryptic (not to mention it assumes you have no script-supporting elements or nested tables within this table) and you're better off just listing all the descendants you want explicitly.

这篇关于CSS选择另一个元素的多个后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆