Can CSS Select Elements Based on Their Child Elements?

Patricia Arquette
Release: 2024-11-21 04:16:12
Original
677 people have browsed it

Can CSS Select Elements Based on Their Child Elements?

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

elements that contain a element?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template