-1

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?

Johannes
  • 64,305
  • 18
  • 73
  • 130
  • in css you can select any **next** siblings via the selector : `div ~ *` for your case here . see for more about selectors https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors – G-Cyrillus Sep 09 '20 at 17:34
  • Adding this to show that there is no previous sibling selector: https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector – disinfor Sep 09 '20 at 17:40

2 Answers2

1

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

Shane Richards
  • 341
  • 1
  • 2
  • 9
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.

Johannes
  • 64,305
  • 18
  • 73
  • 130