0

I would like to change the style of a <span /> which is not a child element of the input. I tried to find the <span /> with + and >, but I could never change it.

Is it possible to change style of it with pure css/scss?

#input:hover,
#input:focus-within {
  span { color: red; }
}
<input type="search" id="input" value='' />
<div>
  <span>My colour should change when hovering the input.</span>
</div>
Malena T
  • 341
  • 2
  • 7
  • 22

2 Answers2

2

Use the adjacent sibling and child combinators like:

#input:hover+div>span,
#input:focus-within+div>span {
  color: red;
}
<input type="search" id="input" value='' />
<div>
  <span>My colour should change when hovering the input.</span>
</div>

Note that the child (>) combinator isn't required but it makes sure you only select the span that's a child and not all span descendants should there be others. You could also use the general sibling combinator (~) instead of the adjacent one, but again the specificity seems more helpful in your case.

j08691
  • 204,283
  • 31
  • 260
  • 272
1

you can try this code:

input[type="search"]#input:hover ~ div span {
   color: red; 
}
<input type="search" id="input" value='' />
<div>
  <span>My colour should change when hovering the input.</span>
</div>
Muhammad Riaz
  • 67
  • 3
  • 10