Search code examples
htmlcss

How to alter my CSS to ensure that the textarea height always matches the height of its div container?


I have a textarea inside a div, and I wish for the text area height to match the height of the div container.

Currently, the width fits perfectly, however the textbox (which begins empty) only fills about 20% of the div height.

And when an ajax call grabs some text and populates the textarea, the textarea height remains at about 20% of the div and provides a scroll bar.

How can I alter my CSS to ensure that the textarea height always matches the height of its div container?

#answerBox {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  margin: 5px auto;
  padding: 5px;
  font-size: 10px;
  text-align: left;
  position: relative;
}

#answerBoxDiv {
  width: 90%;
  min-height: 50%;
  margin: 5px auto;
  border: 4px solid #00bfb6;
  padding: 5px;
  font-size: 10px;
  text-align: left;
  position: relative;
}
<div id="answerBoxDiv">
  <textarea id="answerBox"></textarea>
</div>


Solution

  • You need to explicitly set a height of the parent container (whether that is in px or rem etc) - that way the height: 100% of the textarea will fill to the container.

    The expand on text content cannot be done with simple CSS - you need JS to determine the height of the content and adjust the parent container accordingly.

    The only way you can keep height: 100% on the parent container is if its ancestor has a height set (e.g. 100vh) - that way the browser can determine the height of each DOM element and size the textarea accordingly.

    UPDATE - I have added a JS function to automatically increase the height of the parent container on the input. The textarea auto increases in height since it is 100% of the parent. This will need massaging - but when you type into the textarea, the height will auto expand.

    function setHeight(element) {
      const container = document.getElementById("answerBoxDiv");
      const height = element.scrollHeight;
      if (height > 100) {
        container.style.height = (element.scrollHeight)+"px";
      }
    }
    #answerBoxDiv {
      width: 90%;
      height: 100px; **// this is needed - but can be in px / rem / vh or other but NOT % unless its parent has its height set.**
      margin: 5px auto;
      border: 4px solid #00bfb6;
      padding: 5px;
      font-size: 10px;
      text-align: left;
      position: relative;
    }
    
    #answerBox {
      width: 100%;
      height: 100%; 
      box-sizing: border-box;
      padding: 5px;
      font-size: 10px;
      text-align: left;
      position: relative;
      resize: vertical;
      overflow: hidden
    }
    <div id="answerBoxDiv">
       <textarea id="answerBox" oninput="setHeight(this)"></textarea>
    </div>