I have a Textarea where users can input text. By default it has a height of 17px. However if users insert a large amount of text, I want the text area to expand accordingly. Is there a way to do this with CSS ? Thanks in advance!!
It can be achieved by using JavaScript and jQuery. Method 1: Using JavaScript: To change the height, a new function is created which changes the style property of the textarea. The height of the textarea is first set to auto. This value makes the browser set the height of an element automatically.
For input type="text" , we can use the size attribute to specify the visible size of the field, in characters. But we can also use the maxlength attribute to specify the maximum amount of characters that can be entered. Browsers generally enforce such a limit.
Try textarea {max-width:95%;} - it will always fit your display. Show activity on this post. I set the number of columns to slightly greater that the width of the div on a large screen and as the screen gets smaller it acts responsive to the screen size.
This cannot be done with CSS alone. try the autogrow jquery plugin. https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js
You can also see autogrow demo here http://onehackoranother.com/projects/jquery/jquery-grab-bag/autogrow-textarea.html
It's lightweight and easy to use. Here's how it's done. Define your textarea id. Include the jquery js file before </body>
. Then between script tags, issue the jquery command $("#txtInput").autoGrow();
<body> <textarea id="txtInput"></textarea> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> <script> $("#txtInput").autogrow(); </script> </body>
I know this is a little bit late, but I have to say there is a way to use <div>
with contenteditable
attribute to simulate desired behaviour.
.textareaElement { width: 300px; min-height: 17px; border: 1px solid #ccc; max-height: 150px; overflow-x: hidden; overflow-y: auto; }
<div class="textareaElement" contenteditable></div>
Just set your min and max height, with proper overflow values, and you have fully functional pure CSS expanding textbox, that is also well supported.
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