Home > Web Front-end > CSS Tutorial > Can Sibling Combinators Select :before or :after Pseudo-elements in CSS?

Can Sibling Combinators Select :before or :after Pseudo-elements in CSS?

Susan Sarandon
Release: 2024-12-04 04:30:11
Original
969 people have browsed it

Can Sibling Combinators Select :before or :after Pseudo-elements in CSS?

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

HTML:

<a href="http://google.com">Test</a>
<a href="http://google.com">
    <img src="https://www.google.com/logos/classicplus.png">
</a>
Copy after login

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!

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