CSS Selector for Elements with a Specific Child Element
Question: Is it possible to create a CSS selector that selects all elements that have a specific child element? For instance, to select all
Answer:
Unfortunately, the CSS2 and CSS3 selector specifications do not allow for parent selection. This means that it is not possible to select an element based on its child elements natively.
Recent Developments:
However, the CSS selectors specification has undergone changes recently. While an earlier "Selectors Level 4 Working Draft" included a "subject" feature for selecting the element that should receive styles, this feature was removed in subsequent drafts.
Relational Pseudo-class: :has()
A more recent "Selectors Level 4 Editor's Draft" includes the ":has()" relational pseudo-class, which allows authors to select elements based on their contents. This provides compatibility with jQuery's custom ":has()" pseudo-selector.
Using ":has()", the aforementioned example can be written as:
p:has(span) { color: red; }
This selector will select all
elements that contain a element and style them with a red color. It is important to note that this solution may not be supported uniformly across all browsers.
The above is the detailed content of Can CSS Select Elements Based on Their Child Elements?. For more information, please follow other related articles on the PHP Chinese website!