Home > Web Front-end > CSS Tutorial > How to Select an Element Immediately Before Another Element in CSS?

How to Select an Element Immediately Before Another Element in CSS?

Patricia Arquette
Release: 2024-10-29 05:50:31
Original
504 people have browsed it

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

element. For example:

div + p {
  color: red;
}
Copy after login

In this case, only the first paragraph that follows each

will have red text.

div ~ p (General Sibling Selector)

This selector matches all

elements that are preceded by a

element, regardless of their position. For example:

div ~ p {
  color: blue;
}
Copy after login

In this case, all paragraphs that come after any

element will have blue text.

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

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!

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