-1

Hi I'm trying to do change the style of a div by clicking on an input inside of it. This is my HTML:

<li class="search-bar">
  <form action="" class="search-bar">
    <button class="search-btn">
      <i class="fas fa-search"></i>
    </button>
    <input placeholder="Search term..." type="text" />
  </form>
</li>

SCSS:

.search-btn,
input {
    background: transparent;
}

.search-bar {
    background: $light-grey;
    &:hover {
        background: $light-grey-hover;
    }
    &:focus {
        background: white;
    }
}

When clicking on the input, .search-bar background color doesn't change. I suppose this is because I'm actually focusing on the input inside of it, not the .search-bar div.

How can I make it so that when focusing on the input I can change the style of the whole div containing it? is this possible using css ot should I use a js file?

MrFacundo
  • 167
  • 3
  • 13
  • You cannot select the wrapper (parent) from the child. But you can choose your siblings and achieve what you are expecting – Abin Thaha Jun 16 '21 at 10:45
  • Cool. How can I make the siblings respond to what's happening to one of them? – MrFacundo Jun 16 '21 at 10:46
  • from the duplicate: https://stackoverflow.com/a/46406959/8620333 – Temani Afif Jun 16 '21 at 10:56
  • @termani this is not a duplicate, there is no need of a parent selector (which the duplicate is about at first) .. `:focus-within`answers the question on its own without confusion ;) – G-Cyrillus Jun 16 '21 at 10:57
  • @TemaniAfif oups, i hurted your pseudo on my previous comment (there's probably a more accurate duplicate too) – G-Cyrillus Jun 16 '21 at 11:11
  • @G-Cyrillus we need a parent selector because it's about changing the *parent* style on focus the *child* element. and the duplicate give a lot of way and focus-within is one of them. It's the canonical duplicate for all the child-parent relation (including focus, hover, etc) – Temani Afif Jun 16 '21 at 11:15

1 Answers1

2

You probably could use :focus-within:

.search-bar {
  background: blue;
}

.search-bar:focus-within {
  background: green;
  /* and any style you want to reset */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<li class="search-bar">
  <form action="" class="search-bar">
    <button class="search-btn">
      <i class="fas fa-search"></i>
    </button>
    <input placeholder="Search term..." type="text" />
  </form>
</li>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129