CSS Next Sibling

CSS Next Sibling Element

CSS Next Sibling Element

In CSS, we often need to select the next sibling of an element for styling or other operations. To facilitate this, we can use the “+” symbol in selectors.

Syntax

Using the “+” symbol selects the next sibling of a specified element.


element + selector {
/* styles */
}
  • element: Specifies the element whose next sibling element is to be selected.
  • +: Appended to an element selector, selects the next sibling element of the specified element.
  • selector: The selector for the next sibling element to be selected.

Example

Assume the following HTML structure:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>CSS Next Sibling Element</title> 
<link rel="stylesheet" href="styles.css"> 
</head> 
<body> 
<p>First paragraph</p> 
<p>Second paragraph</p> 
<div>A div element</div> 
<p>Third paragraph</p> 
</body> 
</html> 

We want to select the div element after the second paragraph element and set its background color to gray. We can write CSS like this:

p + div {
background-color: gray;
}

This will select the div element following the second paragraph element and set its background color to gray.

Running Results

Open the above HTML document in a browser and you should see that the background color of the div element following the third paragraph element has changed to gray.

By using the “+” symbol in CSS, we can easily select the next sibling element of a specified element and set its style, achieving more flexible and diverse page layouts and styling effects.

Leave a Reply

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