3

I am referenced with Highlight all elements with same class when one of them is moused over

The way I wanted to know is - Is it possible with CSS?

I am trying with sibling: ~ but it can't highlight previous sibling elements.

.test {
  color: blue;
}
.test:hover, .test:hover ~ .test {
  color: red;
  cursor: pointer;
}
<div>
  <span class="prev">Test Highlight by mouse over the `blue` texts: </span>
  <span class="test">This </span>
  <span class="test">Is </span>
  <span class="test">The </span>
  <span class="test">Highlight</span>
</div>
Alona
  • 549
  • 3
  • 13
  • 1
    This isn't, as you've found - because CSS selectors lack the ability to traverse backwards through the cascade - possible with CSS; but thank you for prompting me to update an answer I'd entirely forgotten about until now. – David Thomas Jun 20 '19 at 18:08
  • Thanks @DavidThomas, so the only the solution is to use `javascript`, right? – Alona Jun 20 '19 at 18:13
  • Unfortunately, yes (CSS [selectors level 4](https://www.w3.org/TR/selectors-4/) has a proposed relational pseudo-class [`:has()`](https://www.w3.org/TR/selectors-4/#relational) that *may* allow for this, but it seems unlikely to make it into browsers in the early days of Selectors level 4. – David Thomas Jun 20 '19 at 18:21

1 Answers1

0

As far as i am aware this is not possible because CSS as of right now is unable to select any preceding elements, though you can achieve this kind of behaviour doing something like this:

.test {
  color: blue;
}
.x:hover .test {
  color: red;
  cursor: pointer;
}
<span class="prev">Test Highlight by mouse over the `blue` texts: </span>
<span class="x">
  <span class="test">This </span>
  <span class="test">Is </span>
  <span class="test">The </span>
  <span class="test">Highlight</span>
</span>

You can read more about CSS being unable to select previous elements here

ivan
  • 1,177
  • 8
  • 23
  • if I can wrap `span`s into one parent element then I don't need this question. And answer is much simple than yours - `x:hover { color: red; }` – Alona Jun 20 '19 at 18:10
  • ```x:hover > span { color: red; }```* but yeah, there is not much to it either that or JS – ivan Jun 20 '19 at 18:13