Can Sibling Combinators Target :before or :after Pseudo-Elements?
In CSS, sibling combinators are used to apply styles to elements that share the same parent but do not nest within one another. However, can these combinators be used to target pseudo-elements, such as :before and :after?
The Challenge
Consider the following CSS and HTML code:
CSS:
a[href^="http"]:after { content:""; width:10px; height:10px; display:inline-block; background-color:red; } a[href^="http"] img ~ :after { display:none; }
HTML:
<a href="http://google.com">Test</a> <a href="http://google.com"> <img src="https://www.google.com/logos/classicplus.png"> </a>
The Intent
This CSS aims to add a red marker to anchors that begin with "http," but it should not add the marker to anchors that contain an image. Since anchor tags cannot be targeted directly using img elements, it's hypothesized that sibling combinators could target the :after pseudo-element of anchor tags that have image siblings.
The Issue
However, this CSS doesn't work as intended. The pseudo-element is not hidden for anchors that contain an image.
The Explanation
The reason for this behavior lies in the nature of pseudo-elements. Pseudo-elements are not part of the DOM tree and are generated by the browser. As a result, sibling combinators cannot target them directly.
The CSS specification states: "Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing)."
The Solution
To achieve the desired effect, JavaScript must be employed. A script could iterate through the anchor tags and add or remove the desired styling based on their image content.
The above is the detailed content of Can Sibling Combinators Select :before or :after Pseudo-elements in CSS?. For more information, please follow other related articles on the PHP Chinese website!