skip to Main Content

I’m trying to make an input where I focus on the input field it removes the placeholder. My code looks as following…

HTML:

<div className="container">
  <input id="input" placeholder="username" />
</div>

I have tried using the ~ operator as following in sass…

#input {
  height: 30px;
  &::placeholder {
     display: flex;
     padding-left: 6px;
   }
  &::focus {
    & ~ .input::placeholder {
      display: none
  }
}
and also the focus-within as following...
#input {
  height: 30px;
  &:focus-within {
     #input::placeholder{
        padding-left: 100px;
     }
   }
  &::placeholder {
     display: flex;
     padding-left: 6px;
   }
  &::focus {
    // set somehow #input::placeholder { display: none }
  }
}

But neither of these work so I would like to know how this is possible in SaSS. I know I could do this with js, but would want to do it in css.

fiddle with the idea..
https://jsfiddle.net/o0qftx3b/13/

2

Answers


  1. Use &:focus::placeholder where you set the color to transparent:

    #input {
      height: 30px;
      
      &:focus::placeholder {
    
          color: transparent;
    
      }
    }
    
    

    #input {
      height: 30px;
      
      &:focus::placeholder {
    
          color: transparent;
    
      }
    }
    <div className="container">
      <input id="input" placeholder="username" />
    </div>
    Login or Signup to reply.
  2. You need to set the opacity of the ::placeholder, since it’s not necessarily a pseudo-element like ::before or ::after. It represents attribute text, which doesn’t necessarily adhere to the display property.

    You can use this:

    #input {
      height: 30px;
      &::placeholder {
        padding-left: 6px;
      }
      &:focus,
      &:focus-within {
        &::placeholder {
          opacity: 0;
        }
      }
    }
    <div className="container">
      <input id="input" placeholder="username" />
    </div>

    As a side note:

    & ~ .input::placeholder { display: none
    That would mean a sibling of the #input element on focus

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search