0

How can I make it so that on Focus on input to change the background color of text ..? What exactly am I doing wrong? please let me know.. thanks

.parent_div {
  background: lightblue;
  .child_div {
    input {
      color: grey;
      background: blue;
      &:focused {
        color: purple;
        background: white;
      }
      &:focused~grand-child-of-parent {
        opacity: 0.7;
        background: red;
      }
    }
  }
}
<div class="parent_div">
  <div class="first_child">
    <input type="text" />
  </div>
  <p class="second_child"> is simply dummy text of the printing and typesetting industry.</p>
</div>
Wajahat Anjum
  • 31
  • 1
  • 5
  • Possible duplicate of [CSS: Change parent on focus of child](https://stackoverflow.com/questions/24287192/css-change-parent-on-focus-of-child) – ReSedano Feb 20 '19 at 09:07

2 Answers2

1

Unfortunately, this is not possible, as there is no "grand-child-of-parent" selector.

You can change the background and text of the input itself, when it gets focudes, but you can't modify styles of parent elements without using JavaScript.

For this case, listen to the focus event by JavaScript and add / remove a modifier class to e.g. parent element.

HTML:

<div class="parent-class">
  <input class="field" type="text" />
  <div class="child-class">
    <p>Bla</p>
  </div>
</div>

CSS:

.child-class {
  background: red;
}
.focused .child-class {
  background: green;
}

JavaScript (jQuery):

$('.field').on('focus', function() {
  $(this).parent().addClass('focused');
})
$('.field').on('blur', function() {
  $(this).parent().removeClass('focused');
})
Mikel Wohlschlegel
  • 1,364
  • 1
  • 11
  • 23
1

Actually this is now kinda possible, but not for any circumstances probably:

With the help of :focus-within (https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within).

.parent_div {
  background: lightblue;
}

.parent_div .first_child .input {
  color: grey;
  background: blue;
}

.parent_div .first_child .input:focus {
  color: purple;
  background: white;
}

.parent_div:focus-within {
  opacity: 0.7;
  background: red;
}
<div class="parent_div">
  <div class="first_child">
    <input class="input" type="text" />
  </div>
  <p class="second_child"> is simply dummy text of the printing and typesetting industry.</p>
</div>