입력 필드 자동 크기

CSS field-sizing

입력 내용에 맞춰 textarea 같은 폼 필드의 크기가 자랍니다.

···
html
<div class="v"><header>FIELD SIZING <span id="lines">1 line</span></header><div class="stage field"><textarea id="text" aria-label="Growing note">A short note</textarea><div class="limit">max-height boundary</div></div><div class="muted">field-sizing: content</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.field{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px}.field textarea{field-sizing:content;min-height:38px;max-height:72%;width:70%;max-width:360px;resize:none;overflow:auto;padding:8px;border:2px solid var(--accent);border-radius:8px;background:var(--bg);color:var(--fg);font:inherit}.limit{width:70%;border-top:1px dashed var(--muted);text-align:center;color:var(--muted)}
js
const t=document.getElementById("text"),lines=["A short note","A short note\nMore detail","A short note\nMore detail\nOne more line"];let i=0;function tick(){t.value=lines[i];document.getElementById("lines").textContent=(i+1)+" line"+(i?"s":"");i=(i+1)%lines.length}tick();let timer=setInterval(tick,950);t.addEventListener("pointerdown",()=>clearInterval(timer))

`field-sizing: content`를 쓰면 textarea나 입력 필드가 기본 고정 크기 대신 내용에 맞춰 자랄 수 있습니다. 자바스크립트로 높이를 반복 측정하던 단순한 자동 확장 입력창을 CSS로 만들 수 있습니다.

데모에서 문장이 한 줄씩 추가되며 textarea 높이가 늘어납니다. 부모의 최대 크기와 스크롤 처리도 함께 정해야 지나치게 긴 입력이 화면을 밀지 않습니다.

언제 쓰나

메시지 작성창이나 짧은 메모 필드를 내용만큼 확장할 때 씁니다.

페이지로 열기 ↗