How CSS Selects Elements Based on Another Element's State
Identifying and targeting elements based on the states of other elements in the DOM can be challenging. CSS selectors offer limited options due to constraints imposed by combinators and selector syntax. While some basic techniques can be applied, including parent-child relationships and the use of pseudo-classes, certain scenarios require more advanced solutions.
Limitations of Current Implementations
Selectors 3, the current standard, lacks essential features like a parent selector or a previous sibling selector. These features would greatly expand the capabilities of CSS for structuring and targeting elements. The inability to specify the subject of a selector also presents a constraint.
Potential in Upcoming Selectors 4
The upcoming Selectors 4 standard aims to address these limitations. The :has() pseudo-class, inspired by jQuery's functionality, provides a flexible solution. :has() enables the selection of elements based on the presence of other elements within their parent.
Solving the Problem
The example problem presented in the question, which requires targeting elements based on another element's data-status attribute, can be solved using :has() in Selectors 4:
section:has(> div[data-status~=finished]) + section > div:matches(.blink, .spin)
This selector achieves the desired result by using :has() to select sections that contain a child div with the specified data-status, and then targeting subsequent sections' div elements that match either the .blink or .spin classes.
The above is the detailed content of How Can CSS Selectively Target Elements Based on a Sibling's Attribute?. For more information, please follow other related articles on the PHP Chinese website!