是一个css框架,本质上是一个工具集,包含了大量className工具类,使用tailwand框架达到的效果,只需要在html里写样式即可,不需要写额外的css代码,达到css in js以及css 语义化的目的。
tailwind的工作原理就是扫描html、js组件或者其他模版里的css类名,然后生成相应的代码到静态的css文件中。
安装
-
创建
tailwind.config.js配置文件/** @type {import('tailwindcss').Config} */ module.exports = { content: ["./src/**/*.{html,js}"], theme: { extend: {}, }, plugins: [], } -
添加指令到项目主css文件中
@tailwind base; @tailwind components; @tailwind utilities; -
Postcss插件配置
plugins: { tailwindcss: {}, autoprefixer: {}, }
简单使用
div class="chat-notification">
<div class="chat-notification-logo-wrapper">
<img class="chat-notification-logo" src="/img/logo.svg" alt="ChitChat Logo">
</div>
<div class="chat-notification-content">
<h4 class="chat-notification-title">ChitChat</h4>
<p class="chat-notification-message">You have a new message!</p>
</div>
</div>
<style>
.chat-notification {
display: flex;
max-width: 24rem;
margin: 0 auto;
padding: 1.5rem;
border-radius: 0.5rem;
background-color: #fff;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
.chat-notification-logo-wrapper {
flex-shrink: 0;
}
.chat-notification-logo {
height: 3rem;
width: 3rem;
}
.chat-notification-content {
margin-left: 1.5rem;
padding-top: 0.25rem;
}
.chat-notification-title {
color: #1a202c;
font-size: 1.25rem;
line-height: 1.25;
}
.chat-notification-message {
color: #718096;
font-size: 1rem;
line-height: 1.5;
}
</style>
<div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4">
<div className="shrink-0">
<img className="h-12 w-12" src={viteLogo} alt="ChitChat Logo" />
</div>
<div>
<div className="text-xl font-medium text-black">ChitChat</div>
<p className="text-slate-500">You have a new message!</p>
</div>
</div>
可以看到,代码量上有比较大的缩减,但是class类很多。
官方描述有三个方面的好处:
- 不需要在起类名上花费时间和精力
- css文件不会继续增长
- 更改样式,在html中修改类名,不需要考虑是否会影响到其他地方