Connect with us

CSS

When Should I Use the Adjacent Sibling Selector (+) in CSS?

Spread the love

In CSS, selectors allow you to target elements with precision. One powerful but often underused selector is the adjacent sibling combinator (+). It lets you apply styles to an element only if it directly follows another specified element.

So, when and why should you use it? Let’s explore.


✅ What Is the Adjacent Sibling Selector (+)?

The adjacent sibling selector selects an element that is the immediate next sibling of another element.

📌 Syntax:

A + B {
  /* Styles */
}

This will target the first <B> element that comes immediately after an <A> element, and they must share the same parent.


🎯 When to Use the Adjacent Sibling Selector

Here are common and effective use cases:


🔹 1. Styling Based on Preceding Elements

If you want to style an element only when it follows a specific element, the + selector is ideal.

h2 + p {
  margin-top: 0;
}

✅ Removes extra space from a paragraph only if it comes right after an <h2>.


🔹 2. Creating Step-by-Step Form Feedback

You can display validation messages right after inputs dynamically:

input:invalid + .error {
  display: block;
  color: red;
}

✅ Shows an .error message only when the <input> is invalid.


🔹 3. Styling Active or Hover-Based UI Elements

input[type="checkbox"]:checked + label {
  font-weight: bold;
}

✅ Highlights the <label> only when the associated checkbox is checked.


🔹 4. Styling Revealed Content Without JavaScript

You can toggle sections using checkboxes or details/summary elements, styling only the element directly after.

details + div {
  border-top: 1px solid #ccc;
}

✅ Adds a border to the content just after a <details> element.


❗ Important Notes

  • The adjacent sibling must be immediately after the first element — no other elements in between.
  • Both elements must share the same parent.
  • It only targets one element, not all following siblings (for that, use ~).

🧾 Summary Table

Use CaseExample SelectorDescription
Remove spacing after headersh2 + pStyles the first paragraph after a heading
Show error messagesinput:invalid + .errorShows error if input is invalid
Style labels or descriptionsinput:checked + labelHighlights label after checked input
Toggle nearby elements visuallydetails + divApplies styles to content after a toggler

🧠 Conclusion

Use the adjacent sibling selector (+) when you want to style an element that immediately follows another — whether for structure, validation, or interactive UI feedback.

It’s a clean, JavaScript-free way to create contextual and reactive designs based on the position of elements.


Pro Tip: Combine + with pseudo-classes like :hover, :checked, or :invalid for smart, dynamic UI interactions.


Spread the love
Click to comment

Leave a Reply

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