CSS next element

CSS Next Element

CSS Next Element

In CSS, by using the Next Adjacent Selector Next-next-next selectors are used to select the next element of an element, applying styles only if they are adjacent siblings.

Next-next-next selectors are denoted by the “+” symbol. In a selector, you first select an element, followed by the “+” symbol, and then the selector for the next element to be selected.


Grammar

element1 + element2 {
/* CSS style */
}
  • element1: The element to be selected
  • +: The next-next-adjacent selector symbol, indicating that it selects the element immediately following element1
  • element2: The next-next-adjacent element to be selected

Example

Let’s take a look at how to use the CSS next element selector with a simple example. Suppose we have an HTML structure as follows:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Next Element Example</title>
<style>
.item {
background-color: #f0f0f0;
padding: 10px;
margin-bottom: 10px;
}

.item + p {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div class="item">First div</div>
<p>Paragraph next to the first div</p>
<div class="item">Second div</div>
<p>The paragraph immediately following the second div</p>

</body>

</html>

In the example above, we define two <div> elements with the class item, each followed by a <p> element. We use the next-next selector .item + p to select the <p> element immediately following the .item element and set its text color to red and bold.

Result

In the example above, both <p> elements following the .item element are styled, with their text color changed to red and bold.

Using the CSS next element selector, we can conveniently select and style the next element immediately following an element, which is very useful in certain layout designs. When you need to differentiate the design of adjacent elements, the CSS next element selector can help you achieve this.

In short, mastering the use of the CSS next element selector allows you to more flexibly control the style relationships between page elements and optimize the page layout.

Leave a Reply

Your email address will not be published. Required fields are marked *