如何使用TailwindCSS实现输入框placeholder动画上浮为标签的效果
TailwindCSS实现浮动标签输入框方案
完全可以实现你要的效果,你参考的是Vue生态下Vuetify组件库的外描边浮动标签输入框,仅用TailwindCSS配合原生HTML就能实现,不需要依赖任何前端框架。
核心实现逻辑
- 利用
:placeholder-shown伪类判断输入框是否已输入内容 - 利用
:focus伪类判断输入框是否处于激活状态 - 借助Tailwind内置的
peer状态选择器和过渡类,实现标签平滑位移、缩放、变色的动画效果
最简实现代码
无需额外自定义CSS,直接使用Tailwind v3原生类即可:
<div class="w-96 mx-auto mt-10"> <!-- 输入框主体 --> <div class="relative"> <input type="text" id="visit-link" class="w-full px-4 pt-6 pb-2 border border-gray-300 rounded-md outline-none focus:border-blue-500 transition-all peer" placeholder=" " > <label for="visit-link" class="absolute left-4 top-4 text-gray-500 transition-all duration-200 origin-top-left pointer-events-none peer-focus:top-2 peer-focus:scale-75 peer-focus:text-blue-500 peer:not(:placeholder-shown):top-2 peer:not(:placeholder-shown):scale-75" > 访问链接(选填) </label> </div> <!-- 底部计数区域 --> <div class="flex justify-between mt-1 text-xs text-gray-500 px-4"> <span class="h-4"></span> <span>0 / 200</span> </div> </div>
关键注意点
- 输入框必须设置
placeholder=" "(单个空格),才能让:placeholder-shown伪类正常触发状态判断 origin-top-left设置标签的变换原点为左上角,保证上浮缩小的动效和主流UI库的效果一致pointer-events-none避免标签拦截输入框的点击事件
复刻Vuetify原生样式实现
如果要完全对齐你提供的Vuetify组件的带fieldset外描边效果,可以使用如下代码:
<div class="w-96 mx-auto mt-10"> <div class="relative"> <!-- 外描边fieldset --> <fieldset class="absolute inset-0 border border-gray-300 rounded-md pointer-events-none peer-focus:border-blue-500 transition-all"> <legend class="ml-2 px-1 text-xs text-transparent transition-all">访问链接(选填)</legend> </fieldset> <input type="text" id="visit-link" class="w-full px-3 py-3 bg-transparent outline-none peer relative z-10" placeholder=" " > <label for="visit-link" class="absolute left-3 top-3 text-gray-500 transition-all duration-200 origin-top-left pointer-events-none peer-focus:top-0 peer-focus:scale-75 peer-focus:text-blue-500 peer:not(:placeholder-shown):top-0 peer:not(:placeholder-shown):scale-75" > 访问链接(选填) </label> </div> <!-- 底部计数区域 --> <div class="flex justify-between mt-1 text-xs text-gray-500 px-3"> <span class="h-4"></span> <span>0 / 200</span> </div> </div>
这个版本的外边框在标签上浮时会自动留出对应缺口,和你参考的Vuetify组件效果完全一致。
内容的提问来源于stack exchange,提问作者Nikola-Milovic
相关产品推荐
相关产品推荐

