# フローティングラベル入力欄のCSS実装

> フォーカスまたは入力済みのときにラベルが小さく上へ移動する入力欄。placeholderと:placeholder-shownを使いJSなしで実現します。

- カテゴリ: フォーム
- URL: https://www.css-dictionary.com/recipes/floating-label-input/

## HTML

```html
<div class="field">
  <input type="text" id="name" placeholder=" " autocomplete="name" />
  <label for="name">お名前</label>
</div>
```

## CSS

```css
.field {
  position: relative;
  width: 260px;
}

.field input {
  width: 100%;
  box-sizing: border-box;
  padding: 20px 12px 6px;
  border: 1px solid #cbbfa5;
  border-radius: 6px;
  background: #fff;
  font: inherit;
}

.field input:focus {
  outline: 2px solid #b0413e;
  outline-offset: -1px;
}

.field label {
  position: absolute;
  left: 13px;
  top: 13px;
  color: #8a7d63;
  pointer-events: none; /* ラベル越しに入力欄をクリックできるように */
  transform-origin: left top;
  transition: transform 0.15s, color 0.15s;
}

.field input:focus + label,
.field input:not(:placeholder-shown) + label {
  transform: translateY(-9px) scale(0.72);
  color: #b0413e;
}

@media (prefers-reduced-motion: reduce) {
  .field label { transition: none; }
}
```

## 仕組みの解説

鍵は placeholder=" "（半角スペース）です。:placeholder-shown は「プレースホルダが見えている＝未入力」のときに一致する擬似クラスなので、input:not(:placeholder-shown) で「入力済み」を表せます。これとフォーカス時（input:focus + label）の2条件でラベルを transform で縮小移動します。ラベルは本物の label 要素なので、クリックでの入力欄フォーカスや支援技術との関連付けはそのまま機能します。

## 実装のポイント

transformで動かしているのはレイアウト再計算を避けるためです。font-sizeやtopを直接アニメーションさせるとカクつくことがあります。

## AIに依頼するときの文例

JSを使わないフローティングラベル入力欄を作ってください。placeholder=" "と:placeholder-shownで入力済みを判定し、フォーカス時と入力済み時にlabelをtransformで左上に縮小移動させてください。

## 使っているプロパティ

- [position](https://www.css-dictionary.com/property/position.md)
- [transition](https://www.css-dictionary.com/property/transition.md)
- [transform](https://www.css-dictionary.com/property/transform.md)
- [outline](https://www.css-dictionary.com/property/outline.md)

