Select any sibling in CSS

I’m making an AngularJS component and I want to select ANY sibling of a tag, no matter if they’re divs or spans or p. I am looking for something that is CSS native and like div:siblings {color: red;}. Can’t find it anywhere. Do you know if it exists?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The CSS sibling selectors ~ and + only select siblings after a particular element. So those won’t be useful if you want to select also the preceding siblings.

But one thing you can do is the following combination of CSS rules:

.container>* {
  color: red;
}
.xxx {
  color: initial;
}
<div class="container">
  <p>Some Text some Text</p>
  <div>Some Text some Text</div>
  <p>Some Text some Text</p>
  <p>Some Text some Text</p>
  <p class="xxx">This one has the class mentioned in the text</p>
  <p>Some Text some Text</p>
  <span>Some Text some Text</span>
</div>

The first rule selects all direct children of the container (and sets their text color), the second one selects the one sibling which has that class (xxx) and resets its color to the default. This should also be possible with other parameters.

Solution 2

Try using the sibling combinator like this

p.target ~ * {
   color: red;
}
<p>First paragraph</p>
<p class="target">Second paragraph</p>
<p>Third paragraph</p>
<p>Fourth paragraph</p>

You’ll need to target the first instance of the element to apply the style to all siblings as shown in the example above.

https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply