How do I auto-resize text using only CSS?

I need to increase the height of the textarea as it is filled with text. I used to have a JavaScript / JQuery solution for this

 function expandingTextBox(e) {
  $(e).css({'height':'80', 'overflow-y':'hidden'}).height(e.scrollHeight);
 }
 $('textarea').each(function(){
   expandingTextBox(80);
 }).on('input', function() {
    expandingTextBox(this);
 });

      

And it almost served its purpose. In short, I have a popup in my web application and I want to be able to drag objects from another location and unload them in the popup, creating new textareas that resize to fit their content. This function resizes text boxes only as you type into them.

A colleague thinks I can only do this with CSS - no JavaScript or JQuery plugins? Every other solution I've found on interwebs relies on at least some JQuery plugin (and I can't easily load new plugins onto my machine at work). Is there a CSS-only way?

I tried changing the textboxes to a div and using the contenteditable attribute. This caused problems elsewhere (but it explains why).

thanks - Gaweyne

EDIT: If this is not possible with pure CSS, I would take solutions that use JavaScript or JQuery, for which I do not need to download additional plugins.

+3


source to share


2 answers


  • Use event delegation to handle dynamically added items.

  • Move your CSS to your stylesheet.

  • On the input, set the height to 80, then set it to the scroll height.

Excerpt



$('button').on('click', function() {
  $('<textarea/>').appendTo('body').focus();
});

$(document).on('input', 'textarea', function() {
  $(this).height(80).height(this.scrollHeight);
});
      

textarea {
  vertical-align: top;
  height: 80px;
  overflow-y: hidden;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add new textarea</button>
<hr>
<textarea></textarea>
      

Run codeHide result


0


source


hope this helps you.

http://jsfiddle.net/Tw9Rj/463/



textarea#note {
    width:100%;
    direction:rtl;
    display:block;
    max-width:100%;
    line-height:1.5;
    padding:15px 15px 30px;
    border-radius:3px;
    border:1px solid #F7E98D;
    font:13px Tahoma, cursive;
    transition:box-shadow 0.5s ease;
    box-shadow:0 4px 6px rgba(0,0,0,0.1);
    font-smoothing:subpixel-antialiased;
    background:linear-gradient(#F9EFAF, #F7E98D);
    background:-o-linear-gradient(#F9EFAF, #F7E98D);
    background:-ms-linear-gradient(#F9EFAF, #F7E98D);
    background:-moz-linear-gradient(#F9EFAF, #F7E98D);
    background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
}

      

-1


source







All Articles