How to stop placeholder from transitioning back ? (CSS)

Viewed 72

I was trying to create an input field with a transition effect to the placeholder, for that I used a <span> tag to hold the placeholder and transitioned it using the :focus CSS selector It works pretty well but the problem is after we input the text and click anywhere outside the input area/text field area, the placeholder transitions back and overlaps with the text inputted. I want the placeholder to not transition back if the text area currently has text in it. Also, there is one more issue that the text field doesn't get selected if the placeholder is clicked. How can I clear these bugs? I've provided the code below:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Input</title>

  <style>
    body {
      margin: 0px;
    }
    
    #top-heading {
      padding: 1rem;
      text-align: center;
      margin: auto;
      margin-bottom: 1rem;
    }
    
    textarea {
      width: 85%;
      display: block;
      height: 10vh;
      margin: 1.5rem;
      margin-top: 0rem;
      padding: 0.5rem;
      font-size: large;
    }
    
    span {
      position: absolute;
      top: 6rem;
      padding-left: 2.7rem;
      color: rgb(121, 120, 120);
      font-size: larger;
    }
    
    textarea:focus~span {
      color: black;
      font-size: 1.091rem;
      transition: .6s ease;
      transform: translate3d(-1.15rem, -1.9rem, 2rem);
    }
  </style>
</head>

<body>
  <h1 id="top-heading">Input</h1>

  <textarea id="txt-input"></textarea>
  <span>Enter the input</span>
</body>

</html>

1 Answers

Can you please check the below code? Hope it will work for you. You need to give transition: .6s ease; property to span tag instead of textarea:focus~span.

Please refer to this link: https://jsfiddle.net/yudizsolutions/kjfc0z37/

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Input</title>

    <style>
      body {
        margin: 0px;
      }

      #top-heading {
        padding: 1rem;
        text-align: center;
        margin: auto;
        margin-bottom: 1rem;
      }

      textarea {
        width: 85%;
        display: block;
        height: 10vh;
        margin: 1.5rem;
        margin-top: 0rem;
        padding: 0.5rem;
        font-size: large;

      }

      span {
        position: absolute;
        top: 6rem;
        padding-left: 2.7rem;
        color: rgb(121, 120, 120);
        font-size: larger;
        transition: .6s ease;
      }

      textarea:focus~span {
        color: black;
        font-size: 1.091rem;

        transform: translate3d(-1.15rem, -1.9rem, 2rem);
      }

    </style>
  </head>

  <body>
    <h1 id="top-heading">Input</h1>

    <textarea id="txt-input"></textarea>
    <span>Enter the input</span>
  </body>

</html>

Related