To ensure the height: 100%
of the textarea
fills the parent container, you must first set a specific height for the parent container using pixels or rem units.
Expanding text content dynamically cannot be achieved with basic CSS alone. JavaScript is required to calculate the content's height and adjust the parent container accordingly.
For the height: 100%
property to work on the parent container, its ancestor needs to have a predefined height (e.g., 100vh
). This allows the browser to compute the height of each DOM element and resize the textarea
accordingly.
UPDATE - I implemented a JS function to automatically increase the parent container's height when input is detected. The textarea
expands in height as it occupies 100% of the parent container. Further adjustments may be needed, but typing in the textarea
will trigger automatic expansion.
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>