0

I'm trying to get Styled Components to work with selecting the closest span element

<label>
   <span className="">Password</span>
   <input type="password" id="passwordInput" />
</label>
     span {
          position: absolute;
          font-size: 14px;
          height: 40px;
          color: #a2a2a2;
          line-height: 40px;
          right: 0;
          left: 8px;
          cursor: auto;
        }
        input {
          height: 40px;
          padding-left: 8px;
          padding-top: 10px;
          padding-bottom: 10px;
          width: 100%;
          border: 1px solid #dbdbdb;
          background-color: #fafafa;
          border-radius: 3px;
          cursor: auto;
          font-size: 16px;

          &:focus {
            & + span {
              background-color: red;
            }
            outline: #a2a2a2;
            border: 1px solid #a2a2a2;
          }
        }

I'm not sure how to go about it, this is what I'm trying right now and it's not working. Preferably I would like to have them work without giving the span, specific classes.

octaviandd
  • 169
  • 2
  • 19
  • 1
    You can't with CSS. You cannot select a preceding sibling. You can change your markup to put the span AFTER the input element and then use CSS to move them into the position you want. – disinfor Jul 14 '20 at 22:10
  • 1
    Does this answer your question? [Is there a "previous sibling" selector?](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector) – disinfor Jul 14 '20 at 22:10

1 Answers1

0

You are indeed using the Adjacent Sibling Combinator, but it only applies to selectors following the selector on the left -

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

This means that if you were to put the input tag first, then it would work. Unfortunately, there's no such thing as a 'previous sibling' yet, so your best choice would be to think of another way to structure your markup and/or CSS.

tkore
  • 1,101
  • 12
  • 31