Today I Learned - Rocky Kev

TIL How to auto-grow textarea with pure css

POSTED ON:

TAGS:

To autogrow the text area with Javascript:

it's

const growers = document.querySelectorAll(".grow-wrap");

growers.forEach((grower) => {
const textarea = grower.querySelector("textarea");
textarea.addEventListener("input", () => {
grower.dataset.replicatedValue = textarea.value;
});
});

To do it a CSS way:

To do this, you replicate the content of the <textarea> in an element that can auto expand height, and match its sizing.

Same font, same padding, same margin, same border… everything.

See the Pen Easiest Autogrowing Textarea by Chris Coyier (@chriscoyier) on CodePen.

.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;
}

It’s an identical copy, just visually hidden with visibility: hidden;.

If it’s not exactly the same, everything won’t grow together exactly right.

We also need `white-space: pre-wrap;`` on the replicated text because that is how textareas behave.

via The Cleanest Trick for Autogrowing Textareas


Related TILs

Tagged:

TIL the alternate keyword

If 'alternate' appears along with the stylesheet keyword, the linked file is an alternative stylesheet. It won’t be applied to the document, but it will be ready for when we need it.

TIL Logical Properties

For that sweet sweet Internationalization you want to avoid directional words like 'left', 'right', 'top', and 'bottom'.

TIL Using pseudo-classes in your querySelector!

let notTuna = document.querySelectorAll('.sandwich:not(.tuna)')