概述

仅使用 CSS 实现的极简搜索栏,单击图标时可平滑展开。通过利用:focus-within伪类,无需使用JavaScript即可实现交互式动画。

代码

###HTML

<div class="search-container">
  <div class="search-box">
    <input type="text" class="search-input" placeholder="Search..." />
    <button class="search-btn" aria-label="Search">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="11" cy="11" r="8"></circle>
        <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
      </svg>
    </button>
  </div>
</div>

CSS

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  background-color: #f8fafc;
  border-radius: 12px;
}

.search-box {
  position: relative;
  display: inline-flex;
  align-items: center;
}

.search-input {
  width: 56px;
  height: 56px;
  border-radius: 28px;
  border: none;
  outline: none;
  padding: 0 20px;
  font-size: 16px;
  font-family: inherit;
  background-color: #ffffff;
  color: transparent; /* 未聚焦时隐藏文本 */
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.01);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
}

.search-input::placeholder {
  color: transparent;
  transition: color 0.4s ease;
}

/* フォーカス時のスタイル */
.search-box:focus-within .search-input {
  width: 280px;
  padding-right: 56px;
  color: #1e293b;
  cursor: text;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.01);
}

.search-box:focus-within .search-input::placeholder {
  color: #94a3b8;
  transition-delay: 0.2s;
}

.search-btn {
  position: absolute;
  right: 0;
  width: 56px;
  height: 56px;
  border: none;
  background: transparent;
  border-radius: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #64748b;
  pointer-events: none; /* 初期状態ではクリックイベントを下のinputにパスする */
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-btn svg {
  width: 20px;
  height: 20px;
  transition: transform 0.4s ease;
}

/* フォーカス時のボタンスタイル */
.search-box:focus-within .search-btn {
  color: #3b82f6;
  pointer-events: auto; /* 展開時はボタンとして機能させる */
  cursor: pointer;
}

.search-box:focus-within .search-btn:hover {
  color: #2563eb;
}

.search-box:focus-within .search-btn svg {
  transform: scale(1.1);
}