08줄 수에 따라 부드럽게 자라고 라벨은 칸 위쪽에 떠 있는 텍스트 영역
scrollHeight 를 재서 목표 높이를 정하고 현재 높이가 거기로 관성 보간되므로 줄이 늘 때 화면이 덜컥 뛰지 않는다.
쓰임문의하기·후기 작성 폼
MAX_ROWSGROW_LERPLINE_HPAD_TOP

<main class="stage">
<div class="fl is-demo" id="fl" data-demo="1">
<div class="fl__field">
<div class="fl__box" data-r="box">
<input class="fl__input" id="f1" data-r="input" type="text" autocomplete="name">
<label class="fl__label" for="f1" data-r="label">이름</label>
</div>
</div>
<div class="fl__field">
<div class="fl__box" data-r="box">
<textarea class="fl__input fl__area" id="f2" data-r="input" rows="1" autocomplete="off"></textarea>
<label class="fl__label" for="f2" data-r="label">메시지</label>
</div>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 핵심: scrollHeight 로 목표 높이를 재고 실제 높이를 관성 있게 따라가게 한다. 라벨은 진짜 <label for> 이고 칸은 진짜 입력 요소다. 움직임 값은 JS 가 계산하고 CSS 는 모양만 맡는다.
@include stage($stage-paper);
$panel: mix($subject-lilac, $stage-paper, 16%);
$box-bg: $stage-paper;
$fg: $subject-ink;
$mute: mix($subject-ink, $stage-paper, 62%);
$line: mix($subject-ink, $stage-paper, 30%);
$accent: $subject-blue-deep;
$err: $error;
$menu-bg: $stage-paper;
$box-h: 52px;
.fl {
position: relative;
box-sizing: border-box;
width: min(100%, 440px);
padding: $sp-5;
display: flex;
flex-direction: column;
gap: $sp-4;
border-radius: $r-card;
background: $panel;
color: $fg;
font-size: 16px;
line-height: 24px;
font-weight: 500;
}
.fl__field { position: relative; }
.fl__box {
--ln: #{$line};
position: relative;
z-index: 1;
height: $box-h;
border-radius: $r-sm;
background: $box-bg;
box-shadow: inset 0 0 0 1.5px var(--ln), 0 0 0 calc(var(--p, 0) * 3px) rgba($accent, .3);
}
.fl__box[data-up] { --ln: #{$accent}; }
.fl__box::after {
content: "";
position: absolute;
inset: 0;
z-index: 0;
border-radius: inherit;
background: $accent;
opacity: calc(var(--p, 0) * .12);
pointer-events: none;
}
.fl__input {
position: relative;
z-index: 1;
box-sizing: border-box;
display: block;
width: 100%;
height: 100%;
margin: 0;
padding: $sp-6 $sp-3 $sp-1;
border: 0;
border-radius: inherit;
background: transparent;
color: $fg;
font-family: inherit;
font-size: 16px;
line-height: 24px;
font-weight: 500;
outline: none;
}
.fl__input:focus-visible { outline: 2px solid $accent; outline-offset: 2px; }
.fl__label {
position: absolute;
left: $sp-3;
top: 0;
z-index: 2;
line-height: $box-h;
font-size: 16px;
font-weight: 500;
color: $mute;
white-space: nowrap;
transform-origin: 0 50%;
pointer-events: none;
will-change: transform;
}
.fl__box[data-up] .fl__label { color: $accent; }
.fl__area { resize: none; overflow: hidden; white-space: pre-wrap; }
.fl__box { min-height: $box-h; }
@media (max-height: 250px) {
.fl__field:nth-child(n + 3) { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.fl__label, .fl__box { will-change: auto; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.fl {
position: relative;
box-sizing: border-box;
width: min(100%, 440px);
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
border-radius: 16px;
background: rgb(95.6078431373%, 94.0392156863%, 100%);
color: #17141a;
font-size: 16px;
line-height: 24px;
font-weight: 500;
}
.fl__field {
position: relative;
}
.fl__box {
--ln: rgb(72.7058823529%, 72.3529411765%, 73.0588235294%);
position: relative;
z-index: 1;
height: 52px;
border-radius: 8px;
background: #ffffff;
box-shadow: inset 0 0 0 1.5px var(--ln), 0 0 0 calc(var(--p, 0) * 3px) rgba(10, 79, 232, 0.3);
}
.fl__box[data-up] {
--ln: #0a4fe8;
}
.fl__box::after {
content: "";
position: absolute;
inset: 0;
z-index: 0;
border-radius: inherit;
background: #0a4fe8;
opacity: calc(var(--p, 0) * 0.12);
pointer-events: none;
}
.fl__input {
position: relative;
z-index: 1;
box-sizing: border-box;
display: block;
width: 100%;
height: 100%;
margin: 0;
padding: 24px 12px 4px;
border: 0;
border-radius: inherit;
background: transparent;
color: #17141a;
font-family: inherit;
font-size: 16px;
line-height: 24px;
font-weight: 500;
outline: none;
}
.fl__input:focus-visible {
outline: 2px solid #0a4fe8;
outline-offset: 2px;
}
.fl__label {
position: absolute;
left: 12px;
top: 0;
z-index: 2;
line-height: 52px;
font-size: 16px;
font-weight: 500;
color: rgb(43.5921568627%, 42.862745098%, 44.3215686275%);
white-space: nowrap;
transform-origin: 0 50%;
pointer-events: none;
will-change: transform;
}
.fl__box[data-up] .fl__label {
color: #0a4fe8;
}
.fl__area {
resize: none;
overflow: hidden;
white-space: pre-wrap;
}
.fl__box {
min-height: 52px;
}
@media (max-height: 250px) {
.fl__field:nth-child(n+3) {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.fl__label, .fl__box {
will-change: auto;
}
}(function () {
const root = document.getElementById("fl");
const CLS = {};
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let demo = !reduce;
let raf = 0;
let last = -1;
const offs = [];
function q(sel) {
return root.querySelector(sel);
}
function qa(sel) {
const list = Array.prototype.slice.call(root.querySelectorAll(sel));
return list;
}
function clamp(v, lo, hi) {
return Math.max(lo, Math.min(hi, v));
}
function on(el, type, fn) {
el.addEventListener(type, fn);
offs.push(function () {
el.removeEventListener(type, fn);
});
}
// 좌표 해시: 같은 입력이면 같은 값 0~1. 난수 함수를 쓰지 않고 사인의 소수부만 쓴다.
function hash(x) {
const s = Math.sin(x * 127.1 + 311.7) * 43758.5453;
return s - Math.floor(s);
}
// 지수 접근: 프레임당 비율 per 만큼 목표에 다가간다. f 는 60fps 기준 프레임 수(dt * 60)라 프레임률이 달라도 같은 속도다.
function approach(x, target, per, f) {
return x + (target - x) * (1 - Math.pow(1 - per, f));
}
// 스프링 한 칸: 가속도 = -k (x - 목표) - c v. 반암시적 오일러를 1/120초 이하 부분 스텝으로 쪼갠다.
function springStep(s, target, k, c, dt) {
let left = dt;
while (left > 0) {
const h = Math.min(left, 1 / 120);
s.v += (-k * (s.x - target) - c * s.v) * h;
s.x += s.v * h;
left -= h;
}
}
// 값이 있으면 라벨은 올라가 있어야 한다. 브라우저 자동완성이 값을 채우면 input 이벤트가 없을 수 있어 :autofill 도 함께 본다.
function isFilled(el) {
if (el.value !== "") return true;
try {
return el.matches(":-webkit-autofill");
} catch (err) {
return false;
}
}
let leaveHook = null;
function stopDemo() {
if (!demo) return;
demo = false;
root.removeAttribute("data-demo");
root.classList.remove("is-demo");
resetFields();
}
function frame(ts) {
const dt = last < 0 ? 0.016 : Math.min(0.05, (ts - last) / 1000);
last = ts;
if (demo) script(ts);
step(dt, ts);
render();
raf = requestAnimationFrame(frame);
}
const ro = new ResizeObserver(function () {
relayout();
});
ro.observe(root);
if (document.fonts) {
document.fonts.ready.then(function () {
relayout();
});
}
// 시연 계획: 칸마다 포커스 구간(a~b), 타이핑 시작(s)·글자당 ms(rate)·글. 2초 주기로 되풀이하고 주기 첫머리엔 모두 비운다.
function runPlan(ts) {
const t = ts % 2000;
let changed = false;
for (let i = 0; i < PLAN.length; i += 1) {
const p = PLAN[i];
const f = fields[i];
const isOn = t >= p.a && t < p.b;
const n = t < p.s ? 0 : Math.min(p.text.length, Math.floor((t - p.s) / p.rate) + 1);
const v = p.text.slice(0, n);
if (f.input.value !== v) {
f.input.value = v;
changed = true;
}
if (f.focus !== isOn) {
f.focus = isOn;
changed = true;
if (!isOn && leaveHook) leaveHook(i);
}
}
if (changed) retarget();
}
function resetFields() {
for (let i = 0; i < fields.length; i += 1) {
fields[i].input.value = "";
fields[i].focus = false;
}
retarget();
}
function wire() {
fields.forEach(function (f, i) {
on(f.input, "focus", function () {
stopDemo();
f.focus = true;
retarget();
});
on(f.input, "blur", function () {
f.focus = false;
if (leaveHook) leaveHook(i);
retarget();
});
on(f.input, "input", function () {
retarget();
});
});
}
// 기법: scrollHeight 로 글이 차지할 목표 높이를 재고, 칸의 실제 높이가 그 값으로 지수 접근한다. 줄이 늘 때 한 번에 튀지 않는다.
const MAX_ROWS = 4;
const GROW_LERP = 0.16;
const LINE_H = 24;
const PAD_TOP = 24;
const PAD_BOTTOM = 4;
const MIN_H = 52;
const RISE_PX = 15;
const LABEL_SCALE = 0.74;
const fields = qa("[data-r=box]").map(function (box) {
const input = box.querySelector("textarea") || box.querySelector("input");
const grow = input !== null && input.tagName === "TEXTAREA";
if (input === null) throw new Error("input missing");
if (grow) {
input.style.lineHeight = LINE_H + "px";
input.style.paddingTop = PAD_TOP + "px";
input.style.paddingBottom = PAD_BOTTOM + "px";
}
return {
box: box,
input: input,
label: box.querySelector("label"),
focus: false, up: false, p: 0, h: MIN_H, th: MIN_H, grow: grow
};
});
const PLAN = [
{ a: 200, b: 560, s: 250, rate: 60, text: "Mina" },
{ a: 560, b: 1990, s: 640, rate: 26, text: "Hi! Could we move\nthe call to Friday\nafternoon? Thanks\nMina" }
];
// 글을 끝까지 담는 데 필요한 높이: 높이를 0 으로 눌러 scrollHeight 를 읽는다. 입력이 있을 때와 칸 폭이 바뀔 때만 부른다.
function wanted(f) {
if (!f.grow) return MIN_H;
const ta = f.input;
ta.style.height = "0px";
const need = ta.scrollHeight;
ta.style.height = "";
const cap = PAD_TOP + PAD_BOTTOM + MAX_ROWS * LINE_H;
ta.style.overflowY = need > cap ? "auto" : "hidden";
return clamp(need, MIN_H, cap);
}
function retarget() {
fields.forEach(function (f) {
f.up = f.focus || isFilled(f.input);
if (f.up) f.box.setAttribute("data-up", "");
else f.box.removeAttribute("data-up");
f.th = wanted(f);
if (reduce) {
f.p = f.up ? 1 : 0;
f.h = f.th;
}
});
if (reduce) render();
}
function relayout() {
retarget();
}
function script(ts) {
runPlan(ts);
}
function step(dt, ts) {
const fr = dt * 60;
fields.forEach(function (f) {
f.p = approach(f.p, f.up ? 1 : 0, 0.22, fr);
f.h = approach(f.h, f.th, GROW_LERP, fr);
});
}
function render() {
fields.forEach(function (f) {
const s = 1 - (1 - LABEL_SCALE) * f.p;
f.label.style.transform = "translate3d(0," + (-RISE_PX * f.p).toFixed(2) + "px,0) scale(" + s.toFixed(3) + ")";
f.box.style.setProperty("--p", f.p.toFixed(3));
if (f.grow) f.box.style.height = f.h.toFixed(1) + "px";
});
}
wire();
relayout();
if (reduce) {
render();
} else {
raf = requestAnimationFrame(frame);
}
})();// TextareaGrowLabel - vanilla 판(08-fl-textarea-grow-label) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./TextareaGrowLabel.module.scss";
type Spring = { x: number; v: number };
type Plan = { a: number; b: number; s: number; rate: number; text: string };
type Base = { input: HTMLInputElement | HTMLTextAreaElement; focus: boolean; up: boolean };
type F = Base & { box: HTMLElement; label: HTMLElement; p: number; h: number; th: number; grow: boolean };
export default function TextareaGrowLabel() {
const rootRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const rootEl = rootRef.current;
if (!rootEl) return;
const root: HTMLElement = rootEl;
const CLS = { };
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let demo = !reduce;
let raf: number = 0;
let last: number = -1;
const offs: Array<() => void> = [];
function q(sel: string): HTMLElement {
return root.querySelector(sel) as HTMLElement;
}
function qa(sel: string): HTMLElement[] {
const list: HTMLElement[] = Array.prototype.slice.call(root.querySelectorAll(sel));
return list;
}
function clamp(v: number, lo: number, hi: number): number {
return Math.max(lo, Math.min(hi, v));
}
function on(el: EventTarget, type: string, fn: (e: any) => void): void {
el.addEventListener(type, fn);
offs.push(function (): void {
el.removeEventListener(type, fn);
});
}
// 좌표 해시: 같은 입력이면 같은 값 0~1. 난수 함수를 쓰지 않고 사인의 소수부만 쓴다.
function hash(x: number): number {
const s = Math.sin(x * 127.1 + 311.7) * 43758.5453;
return s - Math.floor(s);
}
// 지수 접근: 프레임당 비율 per 만큼 목표에 다가간다. f 는 60fps 기준 프레임 수(dt * 60)라 프레임률이 달라도 같은 속도다.
function approach(x: number, target: number, per: number, f: number): number {
return x + (target - x) * (1 - Math.pow(1 - per, f));
}
// 스프링 한 칸: 가속도 = -k (x - 목표) - c v. 반암시적 오일러를 1/120초 이하 부분 스텝으로 쪼갠다.
function springStep(s: Spring, target: number, k: number, c: number, dt: number): void {
let left = dt;
while (left > 0) {
const h = Math.min(left, 1 / 120);
s.v += (-k * (s.x - target) - c * s.v) * h;
s.x += s.v * h;
left -= h;
}
}
// 값이 있으면 라벨은 올라가 있어야 한다. 브라우저 자동완성이 값을 채우면 input 이벤트가 없을 수 있어 :autofill 도 함께 본다.
function isFilled(el: HTMLInputElement | HTMLTextAreaElement): boolean {
if (el.value !== "") return true;
try {
return el.matches(":-webkit-autofill");
} catch (err) {
return false;
}
}
let leaveHook: ((i: number) => void) | null = null;
function stopDemo(): void {
if (!demo) return;
demo = false;
root.removeAttribute("data-demo");
root.classList.remove("is-demo");
resetFields();
}
function frame(ts: number): void {
const dt = last < 0 ? 0.016 : Math.min(0.05, (ts - last) / 1000);
last = ts;
if (demo) script(ts);
step(dt, ts);
render();
raf = requestAnimationFrame(frame);
}
const ro = new ResizeObserver(function (): void {
relayout();
});
ro.observe(root);
if (document.fonts) {
document.fonts.ready.then(function (): void {
relayout();
});
}
// 시연 계획: 칸마다 포커스 구간(a~b), 타이핑 시작(s)·글자당 ms(rate)·글. 2초 주기로 되풀이하고 주기 첫머리엔 모두 비운다.
function runPlan(ts: number): void {
const t = ts % 2000;
let changed = false;
for (let i = 0; i < PLAN.length; i += 1) {
const p = PLAN[i];
const f = fields[i];
const isOn = t >= p.a && t < p.b;
const n = t < p.s ? 0 : Math.min(p.text.length, Math.floor((t - p.s) / p.rate) + 1);
const v = p.text.slice(0, n);
if (f.input.value !== v) {
f.input.value = v;
changed = true;
}
if (f.focus !== isOn) {
f.focus = isOn;
changed = true;
if (!isOn && leaveHook) leaveHook(i);
}
}
if (changed) retarget();
}
function resetFields(): void {
for (let i = 0; i < fields.length; i += 1) {
fields[i].input.value = "";
fields[i].focus = false;
}
retarget();
}
function wire(): void {
fields.forEach(function (f: F, i: number): void {
on(f.input, "focus", function (): void {
stopDemo();
f.focus = true;
retarget();
});
on(f.input, "blur", function (): void {
f.focus = false;
if (leaveHook) leaveHook(i);
retarget();
});
on(f.input, "input", function (): void {
retarget();
});
});
}
// 기법: scrollHeight 로 글이 차지할 목표 높이를 재고, 칸의 실제 높이가 그 값으로 지수 접근한다. 줄이 늘 때 한 번에 튀지 않는다.
const MAX_ROWS = 4;
const GROW_LERP = 0.16;
const LINE_H = 24;
const PAD_TOP = 24;
const PAD_BOTTOM = 4;
const MIN_H = 52;
const RISE_PX = 15;
const LABEL_SCALE = 0.74;
const fields: F[] = qa("[data-r=box]").map(function (box: HTMLElement): F {
const input = box.querySelector("textarea") || box.querySelector("input");
const grow = input !== null && input.tagName === "TEXTAREA";
if (input === null) throw new Error("input missing");
if (grow) {
input.style.lineHeight = LINE_H + "px";
input.style.paddingTop = PAD_TOP + "px";
input.style.paddingBottom = PAD_BOTTOM + "px";
}
return {
box: box,
input: input,
label: box.querySelector("label") as HTMLElement,
focus: false, up: false, p: 0, h: MIN_H, th: MIN_H, grow: grow
};
});
const PLAN: Plan[] = [
{ a: 200, b: 560, s: 250, rate: 60, text: "Mina" },
{ a: 560, b: 1990, s: 640, rate: 26, text: "Hi! Could we move\nthe call to Friday\nafternoon? Thanks\nMina" }
];
// 글을 끝까지 담는 데 필요한 높이: 높이를 0 으로 눌러 scrollHeight 를 읽는다. 입력이 있을 때와 칸 폭이 바뀔 때만 부른다.
function wanted(f: F): number {
if (!f.grow) return MIN_H;
const ta = f.input;
ta.style.height = "0px";
const need = ta.scrollHeight;
ta.style.height = "";
const cap = PAD_TOP + PAD_BOTTOM + MAX_ROWS * LINE_H;
ta.style.overflowY = need > cap ? "auto" : "hidden";
return clamp(need, MIN_H, cap);
}
function retarget(): void {
fields.forEach(function (f: F): void {
f.up = f.focus || isFilled(f.input);
if (f.up) f.box.setAttribute("data-up", "");
else f.box.removeAttribute("data-up");
f.th = wanted(f);
if (reduce) {
f.p = f.up ? 1 : 0;
f.h = f.th;
}
});
if (reduce) render();
}
function relayout(): void {
retarget();
}
function script(ts: number): void {
runPlan(ts);
}
function step(dt: number, ts: number): void {
const fr = dt * 60;
fields.forEach(function (f: F): void {
f.p = approach(f.p, f.up ? 1 : 0, 0.22, fr);
f.h = approach(f.h, f.th, GROW_LERP, fr);
});
}
function render(): void {
fields.forEach(function (f: F): void {
const s = 1 - (1 - LABEL_SCALE) * f.p;
f.label.style.transform = "translate3d(0," + (-RISE_PX * f.p).toFixed(2) + "px,0) scale(" + s.toFixed(3) + ")";
f.box.style.setProperty("--p", f.p.toFixed(3));
if (f.grow) f.box.style.height = f.h.toFixed(1) + "px";
});
}
wire();
relayout();
if (reduce) {
render();
} else {
raf = requestAnimationFrame(frame);
}
return () => {
cancelAnimationFrame(raf);
offs.forEach((f) => f());
ro.disconnect();
};
}, []);
return (
<main className={styles["stage"]}>
<div ref={rootRef} className={styles["fl"] + " is-demo"} data-demo="1">
<div className={styles["fl__field"]}>
<div className={styles["fl__box"]} data-r="box">
<input className={styles["fl__input"]} id="f1" data-r="input" type="text" autoComplete="name" />
<label className={styles["fl__label"]} htmlFor="f1" data-r="label">이름</label>
</div>
</div>
<div className={styles["fl__field"]}>
<div className={styles["fl__box"]} data-r="box">
<textarea className={styles["fl__input"] + " " + styles["fl__area"]} id="f2" data-r="input" rows="1" autoComplete="off"></textarea>
<label className={styles["fl__label"]} htmlFor="f2" data-r="label">메시지</label>
</div>
</div>
</div>
</main>
);
}08 줄 수에 따라 부드럽게 자라고 라벨은 칸 위쪽에 떠 있는 텍스트 영역 — 측정 누적면적 59.731% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · css floating label 9가지 — 입력칸 라벨이 스프링·관성으로 움직이는 폼
이 데모가 속한 글
css floating label 9가지 — 입력칸 라벨이 스프링·관성으로 움직이는 폼사용자가 입력칸을 누르는 0.3초 안에 css floating label 이 어떻게 올라가느냐가 폼의 첫인상을 정한다 — 01번 스프링과 02번 노치가 그 0.3초를 계산으로 채운다. 이 글의 데모 전부 보기


