skip to Main Content

I am learning CSS. I have a div which contains a flexible textarea. Now I want the textarea and outer div to auto expand height when the user inputs multiline content in the textarea, and when the textarea is more than 3 rows, stop the expand and scroll the textarea. How should I write the CSS?

Rendered Code:

.outerdiv {
  height: auto;
  display: flex;
}

.outerdiv textarea {
  height: 100%;
  flex-grow: 1;
}
<div class="outerdiv">
  <textarea></textarea>
</div>

2

Answers


  1. I don’t think there is a css solution.

    However this JS kinda does what you want:

    function updateTextarea() {
       var textarea = document.getElementById("textarea");
        // Get line height of the textarea
       var lht = parseInt($('textarea').css('lineHeight'),10);
        // Get lines 
       var scrlht = textarea.scrollHeight;
       var lines = Math.floor(scrlht / lht);
       
       if (lines < 4) {
        textarea.style.height = '15px'
        textarea.style.height = (lines * lht) + 'px'
       }
     }
    textarea {
    line-height: 15px;
    height: 15px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <textarea id='textarea' oninput="updateTextarea()"></textarea>
    </div>

    It does not make the texarea smaller when removing text. But it does grow when you type.

    Login or Signup to reply.
  2. You could adapt this absolute gem of an answer as follows:

    textarea {
      height: 1rem;
    }
    <textarea 
      data-max-height = "48" 
      name="text" 
      oninput='this.style.height = "";this.style.height = Math.min(this.scrollHeight, this.getAttribute("data-max-height")) + "px"'
      >
    </textarea>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search