1

Can I update the style of the parents after element when an input inside it is focused?

The design means I need to use an after element rather than styling the input with a border but i need to update the background colour of the after element when the input is focused. Can I do this just using SCSS / CSS?

HTML

<div class="subscribe__wrapper">
    <div class="subscribe__input">
        <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]"
            placeholder="Your email address">
    </div>
    <button class="next btn-rounded btn-rounded--small ml-min">
    </button>
</div>

SCSS

.subscribe__wrapper {
position: relative;
&:after {
      content: '';
      left: 0;
      right: 0;
      bottom: 0;
      height: 2px;
      background: $border-color;
      position: absolute; 
    }
}

.subscribe__wrapper input:focus {
  .subscribe__wrapper & {
     &:after {
          background: red;
        } 
    }
}
DumbDevGirl42069
  • 891
  • 5
  • 18
  • 47
  • 1
    Hmm, it seems a little tricky -- I'm not sure that it's possible to do exactly what you need with the current element hierarchy. You could use `.subscribe__wrapper:focus-within:after {}`, however it would apply the focus styles when ANY focusable child is in focus, including the button. If you move the `:after` styles into the `subscribe__input` class, you could use `focus-within` more reliably since theres only one focusable element in there – miir May 29 '19 at 00:48
  • related: https://stackoverflow.com/q/39374918/3597276 – Michael Benjamin May 29 '19 at 02:09

1 Answers1

0

With pure CSS and your current markup, no, it's not possible. See this related question.

As suggested in the accepted answer to that question, though, you can modify your markup to add another element after the input and then style it using a sibling selector (+ or ~) when the input is in focus. This new element would have the background instead of putting it on a pseudo element of .subscribe__wrapper.

For example:

.subscribe__wrapper {
  position: relative;
  z-index: 0;
  padding: 12px;
  border: 2px solid blue;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.subscribe__wrapper input:focus + .background {
  background-color: red;
}
<div class="subscribe__wrapper">
  <div class="subscribe__input">
    <input class="mr-medium" type="email" id="fields-emailAdress" required name="fields[email]" placeholder="Your email address">
    <div class="background"></div>
  </div>
  <button class="next btn-rounded btn-rounded--small ml-min"></button>
</div>
cjl750
  • 4,380
  • 3
  • 15
  • 27