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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With