Rolando
Rolando

Reputation: 62624

How to autogrow a textarea with CSS?

Given a textarea that starts off as a small box, single line, is it possible using CSS to automatically grow to have multiple lines as the user types multiple lines up until say a set limit (300px) when a scrollbar would appear with overflow auto with all the inputs?

Upvotes: 31

Views: 54827

Answers (5)

PaulH
PaulH

Reputation: 3049

With Alpine.js, this is a simple solution

<textarea 
    x-data="{
        init() {
            this.resize();
        },
        resize() {
            $el.style.height = '80px';
            $el.style.height = Math.min(300, $el.scrollHeight + 10) + 'px';
        },
    }"
    x-on:input="resize()"
></textarea>

Upvotes: 2

Evolveye
Evolveye

Reputation: 21

In the future you will be able to use field-sizing CSS property [MDN field-sizing]. Currently (end of the year 2024) it is experimental feature with limited availability [caniuse]

It came to Chromium-based browsers in 2024-03, WebKit and Gecko will possibly follow.

textarea {
  field-sizing: content;
}

<textarea style="field-sizing: content;">
Try it 
</textarea>

Upvotes: 2

Zachary Dahan
Zachary Dahan

Reputation: 1499

2020 Update - Using contenteditable

Because this answer still helps some folks from time to time, I felt like updating my answer with Chris Coiyer's latest finding.

Be warned, it is still not a CSS3 solution. But it's built-in the browser and recreates the OP's sought behavior.

Using contenteditable HTML attribute on a <div /> will allow the user to edit the text content of a div and expand as the user breaks the line. Then, just deguise your div into a <textarea />.

<div 
  class="expandable-textarea"
  role="textbox"
  contenteditable
>
    Your default value
</div>
.expandable-textarea {
  border: 1px solid #ccc;
  font-family: inherit;
  font-size: inherit;
  padding: 1px 6px;

  display: block;
  width: 100%;
  overflow: hidden;
  resize: both;
  min-height: 40px;
  line-height: 20px;
}

The one caveat to this solution, is we're not using textareas. Bear in mind some of the features, such as placeholder, will require some creativity to be implemented using a <div contenteditable />

Source: The Great Chris Coiyer. Link to his blog


Original Answer: Workaround using a light-weight JS lib

Unfortunately, it seems that you cannot do this with only CSS3.

But, there's a 3.2k minified JS alternative to do so.

Here's the link including demo and usage.

You can install it by doing npm install autosize and using this way

autosize(document.querySelector('.yourTextAreaClass'));

Or jQuery style

autosize($('.yourTextAreaClass'));

And it works like a charm. It's lightweight and has a natural feel unlike many autoresize that are doing useless animations.

Upvotes: 20

TylerH
TylerH

Reputation: 21086

Chris Coyier (of CodePen fame) just posted a grid-based CSS-only implementation of this. From Original CodePen by Chris Coyier - October 30th, 2020

.grow-wrap {
  /* easy way to plop the elements on top of each other and have them both sized based on the tallest one's height */
  display: grid;
}

.grow-wrap::after {
  /* Note the weird space! Needed to preventy jumpy behavior */
  content: attr(data-replicated-value) " ";
  /* This is how textarea text behaves */
  white-space: pre-wrap;
  /* Hidden from view, clicks, and screen readers */
  visibility: hidden;
}

.grow-wrap>textarea {
  /* You could leave this, but after a user resizes, then it ruins the auto sizing */
  resize: none;
  /* Firefox shows scrollbar on growth, you can hide like this. */
  overflow: hidden;
}

.grow-wrap>textarea,
.grow-wrap::after {
  /* Identical styling required!! */
  border: 1px solid black;
  padding: 0.5rem;
  font: inherit;
  /* Place on top of each other */
  grid-area: 1 / 1 / 2 / 2;
}

body {
  margin: 2rem;
  font: 1rem/1.4 system-ui, sans-serif;
}

label {
  display: block;
}
<form action="#0">
  <label for="text">Text:</label>
  <div class="grow-wrap">
    <textarea name="text" id="text" onInput="this.parentNode.dataset.replicatedValue = this.value"></textarea>
  </div>
</form>

License:

Copyright (c) 2020 by Chris Coyier (https://codepen.io/chriscoyier/pen/XWKEVLy)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Upvotes: 22

Adam Reis
Adam Reis

Reputation: 4473

Not possible with just CSS as far as I'm aware, but here's a super tiny Angular directive that works just by checking for new lines. You can easily adjust it to have max rows etc.

angular.module('Shared.AutoGrow.Directive', [])
.directive('autoGrow', function() {
  return {
    restrict: 'A',
    link(scope, element) {
      element.on('input change', () => {
        const text = element[0].value;
        const lines = 1 + (text.match(/\n/g) || []).length;
        element[0].rows = lines;
      });
    },
  };
});

Plain JS solution should be easy to deduce, just need to apply an event listener on the element on input/change and that's it.

Upvotes: 1

Related Questions