一个搜索框,在 md 以上的屏幕上显示正常大小,在手机上显示一个搜索图标,点击搜索图标的时候才弹出搜索框

2023-04-13by@timqian&@tailwindcss-expert.Model: gpt-3.5
timqian

你是一个精通 tailwindcss 的专家,我会描述我写页面的需求,你回复我如何用 tailwindcss class 实现,并用最简洁的方式解释一下原理。除了 tailwindcss 尽量不使用 css

Avatar
timqian

一个搜索框,在 md 以上的屏幕上显示正常大小,在手机上显示一个搜索图标,点击搜索图标的时候才弹出搜索框

Avatar
Avatar

可以使用以下 tailwindcss class 实现:

<div class="relative">
  <input type="text" placeholder="Search" class="py-2 pr-8 pl-3 text-gray-700 rounded-full shadow-md focus:outline-none focus:shadow-outline">
  <button class="absolute top-0 right-0 h-full w-12 text-gray-600 rounded-full hover:bg-gray-200 focus:outline-none focus:bg-gray-200">
    <svg class="h-6 w-6 mt-1" viewBox="0 0 24 24" fill="none" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l5.656 5.657M10.5 15a5.5 5.5 0 1 1 0-11 5.5 5.5 0 0 1 0 11z"/>
    </svg>
  </button>
</div>

这里使用了 relativeabsolute 定位,让搜索框和搜索图标重叠在一起,再使用 pr-8pl-3 使输入框留出右侧空间放置搜索图标,同时 py-2 设置了输入框的垂直内边距,让输入框在垂直方向上居中显示。

当在手机屏幕上显示时,搜索框隐藏,只显示一个搜索图标。这里使用了 h-fullw-12 使搜索图标与输入框等高,并设置固定的宽度,使用 rounded-full 设置搜索图标的圆角,使用 hover:bg-gray-200focus:bg-gray-200 使搜索图标在鼠标悬停或者被聚焦时变成灰色背景。

当点击搜索图标时,弹出搜索框。这里使用了 focus:outline-nonefocus:shadow-outline 使搜索图标在被聚焦时不显示默认的轮廓边框,并添加了阴影效果来表示搜索框已被激活。