Home > Web Front-end > CSS Tutorial > Does CSS :not() Selectively Target Distant Descendant Elements?

Does CSS :not() Selectively Target Distant Descendant Elements?

Linda Hamilton
Release: 2024-12-06 18:58:16
Original
300 people have browsed it

Does CSS :not() Selectively Target Distant Descendant Elements?

Can the CSS :not() Selector Target Distant Descendants?

The CSS3 :not() pseudo-class is intended for excluding elements that match a specified selector. It has limited support for targeting distant descendants.

Implementation and Support

The :not() selector has partial implementation in modern browsers, but its support for targeting distant descendants is limited. It primarily operates on direct children of an element.

Behavior with Distant Descendants

In your example, the :not(p) selector does not affect the

element inside the

, even though it is a descendant of the
. This is because :not() only negates the immediate child selector. The
element matches the :not(p) criteria and its color is set to red. Subsequently, the

element inherits this color from its parent

.

Expected Behavior vs. Actual Behavior

You expected the

element to remain unaffected by the :not() selector, but it inherited the color change. This is not the intended behavior for targeting distant descendants.

Solution

To specifically style only

elements within a

, you should use a more direct selector:

div p {
    color: black;
}
Copy after login

Enhancements in CSS Selectors Level 4

CSS Selectors Level 4 proposes extending :not() to accept complex selectors with combinators. This would allow you to target distant descendants with greater flexibility. Once implemented, you could write selectors like:

p:not(div p) {
    color: red;
}
Copy after login

This selector would target all

elements that are not direct descendants of a

.

The above is the detailed content of Does CSS :not() Selectively Target Distant Descendant 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