# 検索ボックス（クリアボタン付き）のCSS実装

> アイコンとクリアボタンを内蔵した検索入力欄。ブラウザごとに見た目が違う標準の×ボタンを消して、自前のクリアに統一します。

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

## HTML

```html
<form class="search" role="search">
  <span class="search-icon" aria-hidden="true">🔍</span>
  <input type="search" id="q" placeholder="プロパティを検索" aria-label="サイト内検索" />
  <button type="button" id="clear" class="search-clear" aria-label="入力をクリア" hidden>×</button>
</form>
```

## CSS

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

.search input {
  width: 100%;
  box-sizing: border-box;
  padding: 10px 36px; /* 左右のアイコン分の余白 */
  border: 1px solid #cbbfa5;
  border-radius: 999px;
  background: #fff;
  font: inherit;
  font-size: 14px;
}

/* ブラウザ標準の×を消して自前に統一 */
.search input::-webkit-search-cancel-button {
  display: none;
}

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

.search-icon {
  position: absolute;
  left: 14px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 13px;
  pointer-events: none;
}

.search-clear {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: #f3ecd9;
  color: #5c5445;
  font-size: 14px;
  line-height: 1;
  cursor: pointer;
}

.search-clear:hover { background: #e2d8c2; }

.search-clear:focus-visible {
  outline: 2px solid #b0413e;
  outline-offset: 1px;
}
```

## JavaScript

```js
const input = document.getElementById('q');
const clear = document.getElementById('clear');

input.addEventListener('input', () => {
  clear.hidden = input.value === '';
});

clear.addEventListener('click', () => {
  input.value = '';
  clear.hidden = true;
  input.focus(); // クリア後は入力に戻す
});
```

## 仕組みの解説

アイコンとクリアボタンは position: absolute で入力欄に重ね、その分の余白をinputのpaddingで確保します。type="search" の標準クリアボタンはブラウザごとに見た目が異なるため、::-webkit-search-cancel-button で消して自前のボタンに統一。クリア後に input.focus() でフォーカスを戻すのが、続けて入力し直せる小さな気配りです。

## 実装のポイント

form要素にrole="search"を付けると、支援技術のランドマークとして検索欄に直接ジャンプできるようになります。

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

クリアボタン付きの検索ボックスを作ってください。アイコンとクリアボタンをposition: absoluteで内蔵し、標準の×は::-webkit-search-cancel-buttonで無効化、クリア後はフォーカスを入力欄に戻してください。

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

- [position](https://www.css-dictionary.com/property/position.md)
- [appearance](https://www.css-dictionary.com/property/appearance.md)
- [border-radius](https://www.css-dictionary.com/property/border-radius.md)
- [transform](https://www.css-dictionary.com/property/transform.md)
- [pointer-events](https://www.css-dictionary.com/property/pointer-events.md)

