如何使用 Tailwind CSS 设置 HTML 文件输入样式?

问题描述 投票:0回答:2

当我遇到这个问题时,我花了大约 20 分钟在这里的一篇文章中找到答案:https://www.kindacode.com/snippet/how-to-style-file-inputs-with-tailwind-css/

我在 Stackoverflow 上浏览了许多关于现有类似问题的过于复杂的答案

将解决方案贴在这里,方便大家快速找到答案


按照此处问题中提供的示例设置输入类型=“文件”按钮的样式我尝试了一堆不太令人满意的解决方案

我尝试将输入包装在标签元素中并将显示设置为无

<label className="text-sm bg-stone-200 hover:bg-stone-300" htmlFor="fileUpload">
    <input type="file" className="hidden" id="fileUpload"/>
    Upload File
</label>

这有效,但随后你会丢失文件名预览 - 解决方案涉及在标签和隐藏输入之间放置

<span>
并更改 onChange 事件中的 span 元素。我认为对于这样一个简单的代码来说,代码太多了任务

我还尝试使用元素属性

<input type="file" size={60} />
设置大小,这显然对其他人有效,但当我尝试时没有效果

tailwind-css html-input
2个回答
4
投票

解决方案:

<input
   type="file"
   className="text-sm text-stone-500
   file:mr-5 file:py-1 file:px-3 file:border-[1px]
   file:text-xs file:font-medium
   file:bg-stone-50 file:text-stone-700
   hover:file:cursor-pointer hover:file:bg-blue-50
   hover:file:text-blue-700"
/>

无需任何 onChange 事件处理程序或标签包装器即可为我工作

感谢 KindaCode 上的 Pennywise。我在这里找到解决方案的完整文章: https://www.kindacode.com/snippet/how-to-style-file-inputs-with-tailwind-css/

在 Tailwind CSS 中,您可以将文件修饰符(修饰符只是可以添加到类开头的前缀)与其他实用程序类结合起来,以创建自定义的漂亮文件输入,例如 file:bg-amber-500 、文件:text-sm 等。 当鼠标悬停在文件输入按钮上时,您还可以使用悬停修饰符设置文件输入按钮的样式,如下所示:hover:file:text-amber-700、hover:file:bg-rose-500 等。


0
投票

基于shadcn的风格

<input className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-foreground file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50" id="picture" name="picture" type="file">
© www.soinside.com 2019 - 2024. All rights reserved.