Andrew Andrew - 3 months ago 12
Sass (Sass) Question

CSS/SASS previous child selection

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?

Answer

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;
}
Comments