Home >Web Front-end >CSS Tutorial >How to Select an Element Immediately Before Another Element in CSS?
Understanding the Difference Between div p and div ~ p
In CSS selectors, the plus ( ) and tilde (~) operators both select sibling elements of a specified element. However, their behaviors differ based on the element's position relative to its sibling.
div p (Adjacent Sibling Selector)
This selector matches all
elements that are immediately after a
div + p { color: red; }
In this case, only the first paragraph that follows each
div ~ p (General Sibling Selector)
This selector matches all
elements that are preceded by a
div ~ p { color: blue; }
In this case, all paragraphs that come after any
Clarifying the Question
The question asks for a selector that selects an element that is placed immediately before a given element. This cannot be achieved with the div p or div ~ p selectors.
Adjacent Sibling Selector for Preceding Elements
To select an element that is immediately before another element, you can use the adjacent sibling selector with the reversed order:
X Y
In this syntax, X is the preceding element and Y is the subject of the selector. For example:
p + ul { color: green; }
This selector will apply green text to only the first unordered list after each paragraph.
The above is the detailed content of How to Select an Element Immediately Before Another Element in CSS?. For more information, please follow other related articles on the PHP Chinese website!