CSS for Web Development

0% completed

Previous
Next
Next sibling combinator (+)

The next sibling combinator (+) selects the element that immediately follows a specified element, but only if they share the same parent. This is useful when you want to style an element based on its position relative to another element.

Syntax

selector1 + selector2 { property: value; }

Explanation:

  • selector1 + selector2:
    • Styles the immediate sibling (i.e., the element that comes right after selector1) if it matches selector2.
    • If there is an element between them, selector2 will not be affected.

Example 1: Styling the Paragraph Following a Heading

In this example, only the <p> element immediately following an <h2> element gets special styling. Other paragraphs further down are not affected.

HTML

. . . .

Explanation:

  • Targeting Sibling:
    • The CSS rule h2 + p applies only to the first <p> that directly follows an <h2>.
  • Outcome:
    • The first paragraph after the heading has blue, italic text and no top margin, distinguishing it from subsequent paragraphs.

Example 2: Highlighting the List Item Following a Special Item

In this example, we style a list such that the list item (<li>) that comes immediately after a list item with a special class is highlighted. This effect can be used to create visual emphasis on items that follow an important list entry.

HTML

. . . .

Explanation:

  • Special Item Styling:
    • The list item with the class .special gets its own distinct background.
  • Next Sibling Styling:
    • The rule .special + li applies to the immediately following list item, highlighting it with a different background color and bold text.
  • Outcome:
    • The list clearly distinguishes the item after the special item, creating a visual cue that these items have a particular relationship.

The next sibling combinator (+) is a powerful tool for applying styles to the element that directly follows another specific element. By targeting immediate siblings, you can create refined, context-specific styling effects that enhance the structure and readability of your content without needing additional classes or markup changes.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next