CSS select multiple descendants of another element

后端 未结 2 868
萌比男神i
萌比男神i 2020-12-03 13:54

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

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


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 14:31

    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.

提交回复
热议问题