SnippetUI

Search Bar Động

Thanh tìm kiếm tối giản mở rộng mượt mà khi bạn nhấp vào biểu tượng.

HTMLCSS

Tổng quan

Thanh tìm kiếm tối giản chỉ được triển khai bằng CSS sẽ mở rộng mượt mà khi bạn nhấp vào biểu tượng. Bằng cách sử dụng lớp giả :focus-within, hoạt ảnh tương tác có thể đạt được mà không cần sử dụng JavaScript.

Mã số

###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; /* Ẩn văn bản khi không tập trung */
  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;
}

/* Kiểu khi lấy nét */
.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; /* Pass click events to underlying input initially */
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

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

/* Button style on focus */
.search-box:focus-within .search-btn {
  color: #3b82f6;
  pointer-events: auto; /*Chức năng như một nút khi được mở rộng */
  cursor: pointer;
}

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

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