CSS select first sibling element

CSS Select First Sibling Element

CSS Select First Sibling Element

When doing front-end development, we often need to locate and modify the styles of specific elements on the page. Sometimes we need to select the first sibling of an element. This is where CSS selectors come in handy. In this article, we’ll detail how to select the first sibling using CSS.

What are Sibling Elements?

In HTML, sibling elements are elements that are adjacent to the same parent element. For example, the following HTML code:


<div>
<p>First sibling element</p>
<p>Second sibling element</p>
<p>Third sibling element</p>
</div>

In this code snippet, the three <p> tags are all children of <div>, making them siblings.

Selecting the First Sibling Element with CSS

To select the first sibling of an element, use the + selector in CSS. The + selector selects the immediate sibling element after the specified element. Here’s the basic syntax for selecting the first sibling element using the + selector:

element + selector {
/*style*/
}

Where element is the element to be selected, and selector is the selector used to select the first sibling element.

For example, if we want to select the sibling elements of the first <p> element in the code above and modify their styles, we can write the following:

p + p {
color: red;
}

This will select all <p> elements after the first <p> element and change their text color to red.

Example

Let’s use a specific example to demonstrate how to use CSS to select the first sibling element. Consider a simple HTML page containing a list and a set of paragraph elements. We want to select the sibling element of the first <li> element in the list and change its color to blue.

<!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 selects the first sibling element</title> 
<style> 
li + p {
color: blue;
}
</style> 
</head> 
<body> 
<ul> 
<li>First li element</li> 
<li>Second li element</li> 
<li>Third li element</li> 
</ul> 
<p>First p element</p> 
<p>Second p element</p> 
</body> 
</html> 

In the above example, we use the CSS li + p selector to select the sibling elements of the first <li> element in the list and change their text color to blue. If you copy this code into an HTML file and open it in a browser, you will see that the text color of the first <p> element has indeed changed to blue.

Summary

Through this article, we learned how to use CSS selectors to select the first sibling element of an element. We also demonstrated how to apply this feature in real-world development through a simple example.

Leave a Reply

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