0

I'm trying to make a span background change colors when I focus on an input field. The HTML is as follows:

<div class='parentDiv'>
  <span class='spanClass'>Some text</span>
  <input class='inputClass' type='text' />
</div>

The closest I could come to something that does this is using the + adjacent sibling selector and doing something like this:

input:focus + span {
  background-color: red;
}

But it doesn't quite work because span must come after input. Is there some way for me to make the span background change colors when I focus the input field?

Andrew
  • 497
  • 6
  • 21
  • Possible duplicate of http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector – neilsimp1 Aug 11 '16 at 19:17

1 Answers1

0

Normally, you would need JS to do that. Here's an example using JS that keeps styling in your CSS:

(function() {
  var spanEl = document.querySelector('.parentDiv > .spanClass');
  var inputEl = document.querySelector('.parentDiv > .inputClass');

  // Add "highlighted" class to "spanClass" element on focus event
  inputEl.addEventListener('focus', function() {
    spanEl.classList.add('highlighted');
  });

  // Remove "highlighted" class from "spanClass" element on blur event (un-focus)
  inputEl.addEventListener('blur', function() {
    spanEl.classList.remove('highlighted');
  });
})();
.spanClass.highlighted {
  background-color: red;
}
<div class="parentDiv">
  <span class="spanClass">Some text</span>
  <input class="inputClass" type="text" />
</div>

In your example, though, you could simply float the one element to the left and change the order in the HTML.

.parentDiv { overflow: hidden; }

.spanClass { float: left; }

.inputClass:focus + .spanClass {
  background-color: red;
}
<div class="parentDiv">
  <input class="inputClass" type="text" />
  <span class="spanClass">Some text</span>
</div>

Something to note for the future, though:

The :has() "relational pseudo-class" seems to be in the works for "CSS4". You can also track it here: http://caniuse.com/#feat=css-has

This means that you will (hopefully) be able to do this eventually:

.spanClass:has(+ .inputClass) {
  background-color: red;
}
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34