Explain Codes LogoExplain Codes Logo

Multiple lines of input in ``

html
textarea
css
javascript
Nikita BarsukovbyNikita Barsukov·Aug 6, 2024
TLDR

Swap <input type="text"> for <textarea> when multiple lines of text input are needed. You can customize its size using rows and cols attributes or opt for more control with CSS:

<textarea rows="4" cols="50">Enter multi-line text here...</textarea>

Making <textarea> efficient

<textarea> is more than just a multi-line <input>. It can adapt its size to fit the input dynamically. Add the temptation of initial point insertion without spaces and the power to craft fluid layouts with width: 100%;, and <textarea> starts to personify text usability.

Power-ups for <textarea>

Bulking up <textarea> with CSS and JavaScript gives you super control and interactive properties:

  • No more clumsy size-handling: width and height in CSS become your chief architects in crafting the visual presence of <textarea>.
  • The highness of Height: auto_height(this) function on onInput event has your back in real-time height adjustments during input
function auto_height(elem) { //Make `elem` feel like it's on a rollercoaster elem.style.height = '1px'; elem.style.height = `${elem.scrollHeight}px`; }

For practicality, attach the handle to the <textarea> and let JavaScript work its magic:

<textarea rows="1" onInput="auto_height(this)"></textarea>

Diving deeper into <textarea>

Prowess of <textarea> is endless, but here are a few tools:

Flexibility with viewport

Achieve <textarea> scale alignment with viewport by percentage-based widths in CSS. Say goodbye to rigid cols.

Initial appearance

Have a compact form by setting the rows attribute to a low value and JavaScript dynamically expanding it. This ensures accessibility and appealing starting layout.

Custom styles without tears

Form design harmony is achievable. Applying a custom CSS class to all <textarea> styles such as .auto_height { /* styles */ } ensures readability and style cohesion.