57

I have a textarea with 200px of height, but when I pass that 200px with text I want to have the textarea expanded instead of keeping the 200px of height with a scroll bar.

It is possible to do that only with CSS?

Chris Martin
  • 28,558
  • 6
  • 66
  • 126
swayziak
  • 677
  • 1
  • 6
  • 10
  • 3
    No it is not possible to do only with css –  Apr 07 '13 at 18:15
  • 3
    Here is a great example of what is possible to do with textarea using CSS: http://css-tricks.com/textarea-tricks/ I believe what you are looking for is 7. Auto-resize to fit content. – Mason240 Apr 07 '13 at 19:42
  • 1
    From Mason240's comment, http://css-tricks.com/textarea-tricks/ , **section #7. Auto-resize to fit content** uses jQuery/JavaScript *not* CSS, despite the title. As user1317647 states above, it is not possible with CSS only but requires script. – JonBrave Jun 29 '16 at 11:15
  • see this answer for how to do it with js: https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize (doesn't requite much js, oninput event and `rows = split("\n").length` works well) – localhostdotdev May 09 '19 at 15:59

5 Answers5

74

Instead of textarea , you can use div with contentEditable attribute:

div {
  display: inline-block;
  border: solid 1px #000;
  min-height: 200px;
  width: 300px;
}
<div contentEditable="true"></div>

DEMO

H. Pauwelyn
  • 11,346
  • 26
  • 71
  • 115
Engineer
  • 43,887
  • 11
  • 83
  • 90
  • 1
    +1 Very nice approach. In cases we can replace `textarea` with a `div` it works and is well supported: http://caniuse.com/#feat=contenteditable. – Erick Petrucelli Apr 07 '13 at 18:37
  • Thanks!This is exactly what is was looking for. – swayziak Apr 07 '13 at 18:42
  • How can I remove the border when I select that div? When I select that DIV in Chrome it shows an awful blue border. – swayziak Apr 07 '13 at 19:02
  • @swayziak Maybe [outline](https://developer.mozilla.org/en-US/docs/CSS/outline) is what you're looking for. – Engineer Apr 07 '13 at 19:06
  • 25
    The only problem is that this kind of element isn't passed by defauld when the form is submited, it is necessary to use Javascript to handle this – Marcio Mazzucato Jun 01 '14 at 00:06
  • Agree with Marcio 100% – Richard Peck Apr 14 '15 at 09:02
  • 4
    Cursor didn't appear with this solution in iOS, so unfortunately doesn't quite cut it – andrewb May 01 '15 at 13:14
  • 12
    Another problem is that if you copy and paste formatted text into the box, [you get HTML inserted](http://stackoverflow.com/questions/15125217/convert-html-to-plain-text-in-contenteditable) there. – z0r Aug 14 '15 at 01:06
  • With large texts editing becomes not responsive as in textarea. – scrutari Sep 11 '15 at 14:04
  • You're kinda genius in HTML thank you for your answer. – Vala Khosravi Feb 16 '18 at 13:51
  • 1
    @Engineer is there a more modern answer to this question now or is your answer still the better option? – Beaniie Apr 02 '18 at 21:38
  • 1
    Pressing `Enter` inside the editable area creates a new editable area. That seems like an important bug in the answer. – Shaun Luttin Feb 26 '19 at 00:57
  • Doesn't work on iphone. It highlights like an input and open keyboard but typing does nothing and you can't select the text/move position of text insertion. --also, since you need Javascript to handle it anyway, better to use textarea and handle size change with javascript: `if(textarea.scrollTop!=0) textarea.style.height = textarea.scrollHeight + "px"` and `textarea{ overflow: hidden;resize:none;}` in css – Michael Aaron Wilson Jan 27 '20 at 17:42
7

It is possible to make a textarea expandable by the user, using just CSS. In fact, in some modern browsers, such expandability is even the browser default. You can explicitly ask for it:

textarea { resize: both; }

Browser support is growing but is still limited.

There is typically just a small hint about resizability: a resize handle in the lower right corner. And I’m afraid most users won’t understand this hint.

You cannot make a textarea expand automatically by content using just CSS.

Jukka K. Korpela
  • 178,198
  • 33
  • 241
  • 350
3

No it is not possible to do only with css, but you could use jquery:

$('#your_textarea').on('keydown', function(e){
    var that = $(this);
    if (that.scrollTop()) {
        $(this).height(function(i,h){
            return h + 20;
        });
    }
});
Community
  • 1
  • 1
1

Unfortunately not, but it is very easy with JS:

let el = document.getElementById(`myTextarea`);
el.addEventListener("input", function() {
  if (el.scrollTop != 0)
    el.style.height = el.scrollHeight + "px";
});

In my case I have a list of player names and I am doing this in a loop for each player.

              humansContainer.innerHTML = humans
                .map(
                  (h, i) =>
                    `<div><textarea id="human_${i}" type="text" value="${h}">${h}</textarea></div>`
                )
                .join("");
              humans.forEach((h, i) => {
                let el = document.getElementById(`human_${i}`);
                el.addEventListener("input", function(e) {
                  let name = el.value;
                  if (el.scrollTop != 0)
                    el.style.height = el.scrollHeight + "px";
                  humans[i] = name;
                });
              });
-11

Here's a simple, pure php and html, solution, without need for js, to make the textarea fit to size. HTML: <textarea rows="<?php echo linecount($sometext, 100, 3);?>" cols="100" name="sometext"><?php echo $sometext;?></textarea>

    <?php
   /* (c)MyWeb.cool, 2014
   * -------------------------------------------------------------------------
   *Calculate number of rows in a textarea.
   *  Parms :   $text:      The contents of a textarea,
   *            $cols:      Number of columns in the textarea,
   *            $minrows:   Minimum number of rows in the textarea,
   *  Return:   $row:       The number of in textarea.
   * ---------------------------------------------------------------------- */
   function linecount($text, $cols, $minrows=1) {
   // Return minimum, if empty`
   if ($text <= '') {
    return $minrows;
   }
   // Calculate the amount of characters
   $rows = floor(strlen($text) / $cols)+1; 
   // Calculate the number of line-breaks
   $breaks = substr_count( $text, PHP_EOL );
   $rows = $rows + $breaks;
   if ($minrows >= $rows)   {
    $rows = $minrows;
   }
   // Return the number of rows
   return $rows;
   }
   ?> 

`And this one is even shorter and better:

function linecount($text, $cols, $minrows=1) {
    if ($text <= '') {return $minrows;}
    $text = wordwrap($text, $cols, PHP_EOL);
    $rows = substr_count( $text, PHP_EOL )+1;
    if ($minrows >= $rows) {$rows = $minrows;}
    return $rows;
}
?>
  • 6
    This won't expand the text area on the client side as the user types more text. It's also not a great idea generally - you can't measure text by counting characters unless you're using a monospace font. – Niall Feb 10 '17 at 12:27