143

I am filling a textarea with content for the user to edit.

Is it possible to make it stretch to fit content with CSS (like overflow:show for a div)?

Cave Johnson
  • 6,171
  • 5
  • 36
  • 53
significance
  • 4,381
  • 8
  • 36
  • 55

10 Answers10

321

one line only

<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
j08691
  • 197,815
  • 30
  • 248
  • 265
Martin Prestone
  • 3,491
  • 2
  • 7
  • 8
  • 9
    how does this have only two votes. this is incredible Martin. I just spend 30 minutes trying to solve this. Great work. – Philip Duffney Mar 10 '18 at 23:38
  • 49
    This is great. I'd just like to add that changing `this.scrollHeight + "px"` to `this.scrollHeight + 3 + "px"` makes the textarea big enough to have it not show the scrollbar. – maarten Mar 31 '18 at 13:01
  • 4
    Problem: When the user writes enough to scroll down, it resets the scroll position every time they add a new line with Enter. – Costa Michailidis Oct 26 '18 at 18:11
  • 1
    This works for what I need, but isn't actually an answer to the question, which asked for CSS solution. – Autumn Leonard Feb 07 '19 at 16:34
  • 9
    I know this is an old question, but I have a textarea on an edit page, and it has a value already when the page loads, how can I make it expand to fit content then? – Arootin Aghazaryan Mar 04 '19 at 02:37
  • 3
    @ArootinAghazaryan - You might already have figured a solution out, but for anyone else: Just create a function with the resize code instead of having it inline in the HTML. Then you can call the same function on page load. – M. Eriksson Apr 28 '19 at 13:04
  • I use `event.target.style.height = event.target.scrollHeight + 8 + 'px'`, then trigger this from controls' onChange event, which passes in the control in question to resize. (The 8 removes scrollbars - thanks @maarten - 3 wasn't enough for macOS Chrome.) Accepted answer so complicated I assume it is brittle (on no evidence). – Chris Jun 07 '19 at 09:49
  • it can be hard to catch a page loading, specially if you use vue etc. so this is a simple solution, update on mousemove, and its looks great) onmousemove='this.style.height = "";this.style.height = this.scrollHeight + "px"' – Martin Prestone Nov 28 '19 at 10:23
  • When content is just a single line of text - textarea is about two lines in size for some reason. – Sam Tyurenkov Mar 27 '20 at 23:31
  • @MartinPrestone If you're using Vue, you have access to the `mounted` hook. Use that. – Joe C. Oct 28 '20 at 19:02
  • What if you have an initial value such as a saved value, prior to user input? – Peter Moore Mar 03 '21 at 14:52
  • 3
    Adding `style="overflow: hidden;"` can make scrollbar invisible, instead of manually plus some small px to height. – thetaprime Mar 24 '21 at 06:32
  • i needed to google for this and this is the solution fitting best for my needs. ty – Paulquappe Jul 13 '21 at 08:03
  • @SamTyurenkov That's because the default value of the "rows" attribute is 2. Set rows="1" on the textarea if you want to have the textarea start with an initial height of 1 row – Robin-Hoodie Jul 27 '21 at 06:50
  • @MartinPrestone, onmousemove still requires the user to mouse over the input. I used onfocus='this.style.height = "";this.style.height = this.scrollHeight + "px"' with autofocus='true' - does the job! To be precise, this was for Sweetalert2: inputAttributes: {'autofocus': true, 'onfocus': 'this.style.height = "";this.style.height = this.scrollHeight + 3 + "px"'}, – Ken Nov 08 '21 at 20:31
  • Great answer. However, for those who have applied top and bottom padding to the textarea then you need to subtract it from the scrollheight. – Pawan Singh Jan 28 '22 at 13:05
51

Not really. This is normally done using javascript.

there is a good discussion of ways of doing this here...

Autosizing textarea using Prototype

Community
  • 1
  • 1
Rik Heywood
  • 13,638
  • 9
  • 59
  • 79
8

This is a very simple solution, but it works for me:

<!--TEXT-AREA-->
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>

<!--JAVASCRIPT-->
<script type="text/javascript">
function setHeight(fieldId){
    document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
}
setHeight('textBox1');
</script>
NicB
  • 314
  • 2
  • 2
  • 5
    The height of the box increases with *every* key stroke, not just new lines. Even backspace and delete cause the height to increase. Fix, and you'll get the upvote back. – Birrel Mar 12 '16 at 20:58
  • some browsers like IE don't calculate scrollheight quite correctly, which can cause those kinds of issues. never mind that's happening for me in Chrome as well... – KthProg Apr 24 '17 at 15:45
  • 1
    here's the solution (edit queue is full): ` ` basically you have to set the height to 1px first, due to this: http://stackoverflow.com/questions/10722058/height-of-textarea-increases-when-value-increased-but-does-not-reduce-when-value – KthProg Apr 24 '17 at 15:55
8

Here is a function that works with jQuery (for height only, not width):

function setHeight(jq_in){
    jq_in.each(function(index, elem){
        // This line will work with pure Javascript (taken from NicB's answer):
        elem.style.height = elem.scrollHeight+'px'; 
    });
}
setHeight($('<put selector here>'));

Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.

Chris Dutrow
  • 45,764
  • 62
  • 180
  • 249
4

Another simple solution for dynamic textarea control.

<!--JAVASCRIPT-->
<script type="text/javascript">
$('textarea').on('input', function () {
            this.style.height = "";
            this.style.height = this.scrollHeight + "px";
 });
</script>
Krutika Patel
  • 430
  • 5
  • 14
3

Alternatively, you could use a contenteditable element, this will fit to the text inside.

<div contenteditable>Try typing and returning.</div>

Please note that it's not possible to send this value along in a form, without using some javascript. Also contenteditable will possibly generate HTML-content and allows styling, so this may need to be filtered out upon form submit.

Tim
  • 2,312
  • 23
  • 18
2

Answers here were good but were lacking a piece of code that I had to add to avoid a shrinking that is not welcome when you type for the first time :

var $textareas = $('textarea');
$textareas.each(function() { // to avoid the shrinking
    this.style.minHeight = this.offsetHeight + 'px';
});

$textareas.on('input', function() {
    this.style.height = '';
    this.style.height = this.scrollHeight + 'px';
});
FTW
  • 720
  • 5
  • 17
2

Not 100% related to the question as this is for Angular only.

There is a npm package associated with Angular called @angular/cdk (if using Angular Material Design). There is a property included in this package that can be associated to a textarea called cdkTextareaAutosize. This automatically sets the textarea to 1 line and stretches the textarea to fit the content accordingly. If you are using this library, something like this should work.

<textarea 
  maxLength="200"
  cdkTextareaAutosize
  type="text">
</textarea>
Mario Petrovic
  • 5,868
  • 12
  • 32
  • 54
Martyn93
  • 171
  • 1
  • 8
0

There are a lot of answers here already, but I think some improvement can still be made to the textarea resizing code.

This script snippet will loop over ALL of the textareas on your page, and make sure they resize both on load and on change.

<script>
  document.querySelectorAll("textarea").forEach(element => {
    function autoResize(el) {
      el.style.height = el.scrollHeight + 'px';
    }
    autoResize(element);
    element.addEventListener('input', () => autoResize(element));
  });
</script>

Vanilla JS only, no libraries needed.

dezman
  • 16,081
  • 9
  • 51
  • 87
-2

Solution for React

I used the length of the text that was being displayed and divided that number by 30 (I adjusted this number until it felt right form my App)

{array.map((text) => (
    <textarea                
     rows={text.length / 30}
     value={text}
    ></textarea>
 )}