CSS selector to find the previous sibling of a sibling node
CSS Selector Finds the Previous Sibling of a Sibling Node
In web development, CSS selectors are often used to locate elements and apply styles or manipulations to them. In these cases, it’s sometimes necessary to locate the previous sibling of an element’s previous sibling, which requires specialized CSS selectors.
Introduction to CSS Selectors
CSS selectors are a method for locating HTML elements by their tag name, class name, ID, and other attributes. In CSS, selectors determine which elements will be affected by a style.
Common CSS selectors include:
- Tag selector
- Class selector
- ID selector
- Descendant selector
- Child selector
- Adjacent sibling selector
- Sibling selector
Finding the previous sibling of a sibling using CSS selectors
In CSS, we can use the sibling selector (the +
symbol) to select adjacent siblings of an element. However, if we want to select the previous sibling of an adjacent sibling, the process is a bit more complicated.
For example, in the following HTML structure, we want to select the previous sibling of the previous sibling of the <span>
tag:
<div>
<p>Paragraph 1</p>
<div>Div 1</div>
<span>Span 1</span>
<p>Paragraph 2</p>
</div>
If you want to select the previous sibling of the previous sibling of the <span>
tag (<div>Div 1</div>
) (Paragraph 1</p>
), you can use the following CSS selector:
span ~ div ~ p {
/* Set styles here */
}
The ~
symbol here selects all sibling nodes at the same level. It can be used repeatedly to select more distant sibling nodes.
Example Code
Next, we’ll use a simple example to demonstrate how to find the previous sibling of a sibling node using CSS selectors.
The HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>CSS selector example</title>
<style>
span ~ div ~ p {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div> <p>Paragraph 1
<div>Div 1</div>
<span>Span 1</span>
Paragraph 2
</div>
</body>
</html>
In this example, we use the CSS selector span ~ div ~ p
to select the previous sibling of the previous sibling of the <span>
tag, and then set its font to red and bold.
Running Results
When we open this example code in a browser, we can see that the text <p>Paragraph 1</p>
turns red and bold, proving that we successfully used the CSS selector to find the previous sibling of a sibling.
This example shows that using CSS selectors to find the previous sibling of a sibling is not difficult; with a little practice, you can become proficient in this technique. The power of CSS selectors lies in their ability to flexibly locate elements in different locations and set their styles, greatly facilitating web development.