CSS select multiple descendants of another element
You can now do this with :is() selector. If it requires larger selection, you can exclude the smaller ratio using :not
as a combination with it as in the code snippet:
This selector can be used in latest versions of all the 4 major browsers (Edge, Firefox, Chrome and Safari): https://caniuse.com/?search=is as on 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;
}
<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>
Is it possible to select multiple elements that have an ancestor of a certain class, id, etc in CSS?
This is now possible with the :is()
pseudo-class, originating as :matches()
mentioned in the original version of this answer below. Be sure not to get it mixed up with :where()
, which removes specificity that's otherwise critical to your selector:
table.exams :is(caption, tbody, tfoot, thead, tr, th, td)
Prior to :is()
, this was not possible without duplicating the entire ancestor selector and specifying all of the descendants1:
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)
1Specifically 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.