Home > Enterprise >  How to make changes to the sibling element if child of an element is focused? [duplicate]
How to make changes to the sibling element if child of an element is focused? [duplicate]

Time:10-08

I want to change colour of css.seperator when css.searchBarInput is in focus, how can I do this?

Here's my HTML for reference:

<div className={css.searchBarBase}>
  <div className={css.searchBarFirstDiv}>
    <label className={css.searchBarDivContent} htmlFor="location-search-input">
      <div className={css.searchBarHeadingFont}>Location</div>
      <input
      id="location-search-input"
      className={css.searchBarInput}
      />
    </label>
  </div>

  <div className={css.seperator}/>
</div> 

Here's my attempt at it:

.searchBarBase > div:focus-within   div {
  opacity: 0;
}

CodePudding user response:

If there is only one focusable element inside searchBarBase then you can look at focus-within.

https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.)

selector to use for you would be .searchBarFirstDiv:focus-within ~.seperator {/* style to apply here */}

  • Related