DEV Community

Cover image for Top CSS Sibling Selectors -- An Explanation
OpenReplay Tech Blog
OpenReplay Tech Blog

Posted on

Top CSS Sibling Selectors -- An Explanation

by Nwanadee Emmanuel

The art of web development can be demanding when it has to do styling elements on a webpage, especially in cases where these are part of another component or grouped under a common parent(s). This is where CSS sibling selectors come into play, and this article will tell you everything about them.

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data.

OpenReplay

Happy debugging! Try using OpenReplay today.


With the help of sibling selectors, developers can target elements in HTML pages based on their sibling connections. This powerful CSS feature gives developers exact control over layout, functionality, and style. Developers may simplify their CSS code, produce complex and responsive designs, and enhance the user experience using sibling selectors.

In this article, we will discuss the top CSS sibling selectors, such as adjacent and general sibling selectors, and show their examples, when to use them, their differences, and best practices.

Prerequisites

To follow along with this tutorial, you need:

  • A good knowledge of HTML
  • A basic understanding of CSS

Understanding Adjacent Sibling Selectors in CSS

Adjacent sibling selectors are CSS selectors that target an element coming directly after another one. For styling elements that have relationships closely related to the HTML structure, such as navigation links or list items, adjacent sibling selectors are needed. They allow you to target elements by their position relative to the selected element rather than some global ordering in the actual page structure. The adjacent sibling selectors are denoted by the plus sign (+).

adjacent diag.

In the figure above, the block with the red color is the selected block affected after using the adjacent sibling selector. It is affected because the paragraph element comes immediately after the h1 element.

Syntax

The syntax for adjacent sibling selectors is:

.element + .sibling
Enter fullscreen mode Exit fullscreen mode

Here:

.element is the targeted element selector.
+ is your adjacent sibling combinator.
.sibling selects the element immediately following .element

The + symbol indicates that the selector should target the element directly after .element in the HTML structure.

Code Examples

Here are some code examples illustrating how the adjacent sibling selector targets elements:

Example 1

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Adjacent Sibling Selector Example 1</title>
    </head>
    <body>
        <p class="paragraph">This is a paragraph</p>
        <p class="sibling">This is another paragraph</p>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

.paragraph + .sibling {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

Output:

adjacent 1

From the output above, the second paragraph is styled with red text because it is the adjacent sibling of the first paragraph.

Example 2

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Adjacent Sibling Selector Example 2</title>
    </head>
    <body>
        <div class="container">
            <p class="paragraph">This is a paragraph</p>
            <span class="sibling">This is a span</span>
            <p class="sibling">This is another paragraph</p>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

.paragraph + .sibling {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Output:

adjacent 2

As the span element is the next sibling of the paragraph element, the result above demonstrates that it is styled with bold text ("This is a span").

Browser Compatibility

The adjacent sibling selector is widely supported across modern browsers. The table below illustrates supported browsers and their versions.

Browsers Version Range
Chrome 1.0+
Firefox 3.0+
Safari 3.2+
Edge 12.0+
Opera 9.2+

Understanding General Sibling Selectors in CSS

In CSS, the general sibling selector can target all sibling elements of a selected element, not just adjacent ones. It is used to target all elements that are siblings of the first element, provided they are children of the same parent.

General sibling selectors are helpful for styling elements that share a common parent but are not necessarily adjacent to each other. Unlike the adjacent sibling selectors, they give you more power and flexibility to target elements based on their relationships, not just because the other element is next door.

general diag.

The blocks in the diagram above that are red are the selected blocks after using the general sibling selector. All the paragraph elements are selected because they share a common parent with the h1 element.

Syntax

The syntax for general sibling selectors is:

.element ~ .sibling

Here:

.element is the targeted element selector.
~ is your general sibling combinator.
.sibling selects the element immediately following .element

The ~ symbol indicates that the selector should target all elements that are siblings of .element, regardless of their position in the HTML structure.

Code Examples

Here are some code examples illustrating how the general sibling selector targets elements:

Example 1

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>General Sibling Selector Example 1</title>
    </head>
    <body>
        <div class="container">
            <p class="paragraph">This is a paragraph</p>
            <span class="sibling">This is a span</span>
            <nav class="sibling">This is a nav</nav>
            <div class="sibling">This is a div</div>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

.paragraph ~ .sibling {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

Output:

general 1

The output above shows that all three elements (.sibling) are styled with red text because they are general siblings of the paragraph element.

Example 2

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>General Sibling Selector Example 2</title>
    </head>
    <body>
        <ul>
            <li class="item">Item 1</li>
            <li class="item">Item 2</li>
            <li class="item">Item 3</li>
            <li class="item">Item 4</li>
        </ul>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

.item ~ .item {
    background-color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

Output:

general 2

As shown in the output above, all list items (.item) except the first have a yellow background because they are siblings of the previous list item.

Browser Compatibility

The general sibling selector is widely supported across modern browsers. The table below illustrates supported browsers and their versions.

Browsers Version Range
Chrome 1.0+
Firefox 3.0+
Safari 3.1+
Edge 12.0+
Opera 9.5+

Advantages of Using Adjacent and General Sibling Selectors in CSS

The advantages of using adjacent and general sibling selectors in CSS include:

  • Better styling: They save you the trouble of littering your markup with unnecessary class names or IDs in favor of target elements based on their relationship from a styling perspective. 
  • Clean code: adjacent selectors and general sibling selectors help developers to write clean and organized CSS codes.
  • Flexible work: Complex layouts and designs can be created without the use of HTML table-style structures. 
  • Simpler CSS: These methods avoid overly specific selectors, resulting in reduced complexity and bloat. 
  • Easy maintenance: Easy maintenance: If you use adjacent and general sibling selectors, other parts of your code will not be affected when making changes to CSS.
  • Responsiveness: They help in building responsive designs that adjust according to screen sizes and types of devices. 
  • Improved accessibility: They create clear and consistent navigation and content structure. 
  • Better teamwork: By using sibling and general sibling selectors, you make CSS easier to read and work with. 

By using adjacent and general sibling selectors, you can write more efficient, flexible, and maintainable CSS code, making your web development workflow more productive and efficient.

Key Differences and Use Cases

There are some key differences between adjacent and general sibling selectors, which determine their applications and use cases.

Adjacent Sibling Selector General Sibling Selector
The plus (+) sign is used to denote adjacent sibling selector The tilde (~) sign is used to denote general sibling selector
It is exclusive in making selections It is inclusive in making selections
Adjacent sibling selector can only be used to style consecutive elements. General sibling selector can be used to style multiple elements
It is commonly used to style adjacent elements like navigation links or list items It is used for styling elements with varying HTML structures
Adjacent sibling selector has good performance since it only needs to check the immediate next element General sibling selector has weak performance since it needs to check all sibling elements.

These differences help you choose the appropriate selector for your specific use case.

Some Cases where Adjacent Sibling Selectors are Needed for Efficient Styling

This session will expose us to cases where the adjacent sibling selectors are useful for styling.

Styling list items with specific borders

Adjacent sibling selector can be used to style list items with a specific border.

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

li + li {
    border-top: 2px solid #ccc;
}
Enter fullscreen mode Exit fullscreen mode

Output:

specific border

The output above shows that a top border is added to all list items that are immediately followed by another list item except the first one.

Styling paired elements

The adjacent sibling selector is handy for styling paired elements, such as labels and inputs, headings and paragraphs, or icons and texts.

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h2>Question 1: What is your name?</h2>
        <p>Input your name</p>
        <h2>Question 2: How old are you?</h2>
        <p>Input your age</p>
        <h2>Question 3: What is your gender?</h2>
        <p>Input your gender</p>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

h2 + p{
    font-style: italic;
}
Enter fullscreen mode Exit fullscreen mode

Output:

pair element

All paragraph elements immediately followed by a heading (h2) are italicized.

Some Cases where the General sibling Selectors are Needed for efficient styling

This session will expose us to cases where the general sibling selectors are useful for styling.

Styling all paragraphs following a specific heading

You can use the general sibling selector to style all paragraph elements that follow a specific heading element.

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h2>Heading</h2>
        <p>paragraph 1</p>
        <p>paragraph 2</p>
        <p>paragraph 3</p>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

h2 ~ p {
    color: green;
    font-size: 1.5em:
}
Enter fullscreen mode Exit fullscreen mode

Output:

all paragraph

All paragraph elements that are siblings of the h2 element are styled regardless of their position in the heading.

Applying the hover effect to all list items within a container

A general sibling selector can also help apply the hover effect to all list items within a container.

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div class="container">
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
                <li>Item 4</li>
            </ul>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container ul li ~ li:hover {
    background-color: #eee;
    color: #666;
}
Enter fullscreen mode Exit fullscreen mode

Output:

hovereffect-ezgif

All list items (li) that are siblings of the hovered list item within the container element (div) have a hover effect.

Best Practices

These are some of the best practices for using the adjacent and general sibling selectors. 

  • Keep it simple: Avoid using complex selectors or chaining multiple selectors. 
  • Use for styling purposes: Use the adjacent and general sibling selectors for styling purposes.
  • There should be a sibling relationship: The styling elements must have a sibling relationship.
  • Test and debug: Always test and debug your selectors to ensure they are working as you want. 
  • Consider alternative selectors: Consider using alternative selectors, such as the child selector (>) or the attribute selector, if they better fit the use case.

To use the adjacent and general sibling selectors effectively, ensure that the above best practices are carried out.

Conclusion

In web development, CSS sibling selectors are vital, especially when styling elements with sibling relationships. This article focuses on two types of sibling selectors: adjacent (+) and general (~).

Understanding and properly using adjacent and general sibling selectors allows you to create more efficient and maintainable CSS code.

Top comments (0)