构建 Tailwind CSS 文件上传输入组件
Tailwind CSS 是我最近经常使用的框架,但有一个特殊问题阻碍了我的开发进程:缺少组件。
尽管我喜欢使用实用程序类构建网站的新方法,但我确实怀念在构建新界面时可以立即使用的几个 Web 组件。
这就是为什么我决定在 DEV 社区上开设一个教程系列,向您展示如何使用 Tailwind CSS 中的实用程序类构建常用的 Web 组件。
上次我向您展示了如何构建复选框和单选输入字段,今天我将向您展示如何使用 Tailwind CSS 构建一个美观的文件上传输入组件。
让我们开始吧!
Tailwind CSS 文件上传组件
首先,我们需要设置文件上传输入的 HTML 标记。
<label for="user_avatar">Upload file</label>
<input aria-describedby="user_avatar_help" id="user_avatar" type="file">
<div id="user_avatar_help">A profile picture is useful to confirm your are logged into your account</div>
正如您所见,我们已经添加了for
和id
属性。
让我们给label
元素添加一些样式:
<label class="text-sm font-medium text-gray-900 block mb-2" for="user_avatar">Upload file</label>
<input aria-describedby="user_avatar_help" id="user_avatar" type="file">
<div id="user_avatar_help">A profile picture is useful to confirm your are logged into your account</div>
看起来好多了!现在到了重要的部分:我们需要给输入框本身添加样式。我们来添加一些样式吧。
<label class="text-sm font-medium text-gray-900 block mb-2" for="user_avatar">Upload file</label>
<input class="block w-full cursor-pointer bg-gray-50 border border-gray-300 text-gray-900 focus:outline-none focus:border-transparent text-sm rounded-lg" aria-describedby="user_avatar_help" id="user_avatar" type="file">
<div id="user_avatar_help">A profile picture is useful to confirm your are logged into your account</div>
我们还为下面的帮助文本添加一些样式。
<label class="text-sm font-medium text-gray-900 block mb-2" for="user_avatar">Upload file</label>
<input class="block w-full cursor-pointer bg-gray-50 border border-gray-300 text-gray-900 focus:outline-none focus:border-transparent text-sm rounded-lg" aria-describedby="user_avatar_help" id="user_avatar" type="file">
<div class="mt-1 text-sm text-gray-500" id="user_avatar_help">A profile picture is useful to confirm your are logged into your account</div>
你可能会问:但它看起来仍然不太好。为什么呢?原因是我们仍然需要为输入文件按钮编写一些伪样式。
在为 Post CSS 编译配置的 CSS 文件中添加以下样式:
input[type=file]::-webkit-file-upload-button,
input[type=file]::file-selector-button {
@apply text-white bg-gray-700 hover:bg-gray-600 font-medium text-sm cursor-pointer border-0 py-2.5 pl-8 pr-4;
margin-inline-start: -1rem;
margin-inline-end: 1rem;
}
添加此代码后,带有类的最终 HTML 应如下所示:
恭喜,您已经使用 Tailwind CSS 中的实用程序类构建了一个文件上传组件!
在您离开之前,我想告诉您,这个Tailwind CSS 文件上传组件是一个更大的开源 Tailwind CSS 组件库 Flowbite 的一部分。
您可以查看Flowbite,并使用 Tailwind CSS 中的实用程序类,通过一组常用的 Web 组件(如按钮、警报、导航栏、模式等)开始更快地制作网站。
鏂囩珷鏉ユ簮锛�https://dev.to/themesberg/building-a-tailwind-css-file-upload-input-component-4he4