skip to Main Content

I want to center align textarea with placeholder. so I am using following code

<textarea style="text-align: center" placeholder="Type Here..."></textarea>

But issue is with design. I want to start cursor from starting position of placeholder something like this as like instagram story
enter image description here

but with text-align center it looks like this
enter image description here

I tried different CSS option like padding and setSelectionRange but not working

2

Answers


  1. I think that its not directly possible using just the textarea and placeholder and way you can try is by adding the textarea in a div

        <div style="border: 1px solid;display: flex;align-items: center;justify-content: center;">
    <textarea style="border: none; resize: none;" placeholder="Type Here..."></textarea>
    </div>
    

    You can further style the element as per your need

    Login or Signup to reply.
  2. You can achieve this with java-script included. Here is a solution:

    Html:

    <div class="centered-textarea">
      <textarea id="myTextarea" placeholder="Type Here..."></textarea>
    </div>
    

    Css:

    .centered-textarea {
      text-align: center;
      position: relative;
      width: 100%;
    }
    
    .centered-textarea textarea {
      width: 100%;
      padding: 8px; /* Adjust as needed */
      box-sizing: border-box;
    }
    

    Java-script:

    window.onload = function() {
      var textarea = document.getElementById('myTextarea');
      textarea.addEventListener('input', function() {
        adjustCursor(this);
      });
    
      adjustCursor(textarea);
    };
    
    function adjustCursor(textarea) {
      var placeholderText = textarea.getAttribute('placeholder');
      var placeholderLength = placeholderText.length;
      textarea.setSelectionRange(0, 0);
    }
    

    The Html structure is wrapped in a container div with .centered-textarea. This container will ensure that the textarea is centered within its parent container, the Css makes sure that the textarea class will be centered horizontally & takes up the full width of it’s container, and the Java-script code adjusts the cursor position to the beginning of the textarea whenever the textarea receives input and gets the length of the placeholder text and sets the cursor position accordingly.

    Hope this helps 🙂

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