当前位置: 首页 > news >正文

Tailwind CSS 自定义样式

Tailwind CSS 自定义样式学习笔记

一、自定义样式的层次结构

┌──────────────────────────────────────────────────────┐ │ tailwind.config.js → 设计系统 Token(颜色/间距/字号) │ │ @layer base → 全局基础样式重置 │ │ @layer components → 组件级自定义类 │ │ @layer utilities → 自定义工具类 │ │ @layer 外部 → 第三方/覆盖样式 │ │ arbitrary values → 一次性行内自定义值 │ └──────────────────────────────────────────────────────┘

二、方法一:Arbitrary Values(任意值)

无需修改配置,直接在类名中使用方括号语法写入任意 CSS 值。

基本语法

<!-- 间距 --><divclass="mt-[17px] w-[calc(100%-3rem)] p-[2.5rem]"><!-- 颜色 --><spanclass="text-[#1da1f2] bg-[rgb(59,130,246,0.5)]"><!-- 字体 --><pclass="text-[22px] leading-[27px] font-[500] tracking-[0.01em]"><!-- 动画 --><divclass="animate-[spin_1.5s_linear_infinite]"><!-- 背景图 --><divclass="bg-[url('/hero-pattern.png')] bg-[size:100px_100px]">

任意变体(Arbitrary Variants)

<!-- 任意媒体查询 --><divclass="@[supports(display:grid)]:grid"><!-- 任意选择器 --><divclass="[&:nth-child(3)]:underline"><divclass="[&::before]:content-['→'] [&::before]:mr-2"><!-- 子元素选择器 --><navclass="[&>li]:flex [&>li]:items-center"><!-- 父级上下文 --><divclass="[.dark_&]:text-white">

注意事项

  • 任意值中的空格用_代替:animate-[spin_1s_linear_infinite]
  • 任意值中的逗号用_代替:grid-cols-[repeat(3,1fr)]grid-cols-[repeat(3,1fr)]
  • 仅用于一次性场景,频繁出现应提取到配置中

三、方法二:扩展 Theme 配置

2.1 扩展 vs 覆盖

// tailwind.config.jsmodule.exports={theme:{// ❌ 覆盖 — 完全替换默认值,丢失 Tailwind 默认色板colors:{brand:'#3b82f6',},// ✅ 扩展 — 在默认值基础上追加extend:{colors:{brand:'#3b82f6',},},},};

2.2 自定义颜色

module.exports={theme:{extend:{colors:{// 简单值'brand':'#3b82f6',// 色阶对象(生成 text-brand-50 ~ text-brand-950)brand:{50:'#eff6ff',100:'#dbeafe',200:'#bfdbfe',300:'#93c5fd',400:'#60a5fa',500:'#3b82f6',600:'#2563eb',700:'#1d4ed8',800:'#1e40af',900:'#1e3a8a',950:'#172554',},// CSS 变量引用surface:'var(--color-surface)',on:{surface:'var(--color-on-surface)',},},},},};
<buttonclass="bg-brand-500 text-white hover:bg-brand-600">品牌按钮</button><divclass="bg-surface text-on-surface">主题卡片</div>

2.3 自定义间距 / 尺寸

extend:{spacing:{'4.5':'1.125rem','18':'4.5rem','128':'32rem',},width:{'1/7':'14.2857%','2/7':'28.5714%',},height:{'screen/2':'50vh',},}

2.4 自定义字体

extend:{fontFamily:{sans:['Inter','system-ui','sans-serif'],mono:['JetBrains Mono','Fira Code','monospace'],display:['Cal Sans','sans-serif'],},fontSize:{'xxs':['0.625rem',{lineHeight:'0.875rem'}],'2xl':['1.25rem',{lineHeight:'1.75rem',letterSpacing:'-0.01em'}],},}
<h1class="font-display text-2xl">标题</h1><codeclass="font-mono text-xxs">代码</code>

2.5 自定义动画

extend:{keyframes:{'fade-in':{'0%':{opacity:'0',transform:'translateY(10px)'},'100%':{opacity:'1',transform:'translateY(0)'},},'slide-in-right':{'0%':{transform:'translateX(100%)'},'100%':{transform:'translateX(0)'},},'shimmer':{'100%':{transform:'translateX(100%)'},},},animation:{'fade-in':'fade-in 0.3s ease-out forwards','slide-in-right':'slide-in-right 0.4s ease-out','shimmer':'shimmer 2s infinite',},}
<divclass="animate-fade-in">淡入效果</div><divclass="animate-slide-in-right">右侧滑入</div>

2.6 自定义阴影 / 边框圆角 / 过渡

extend:{boxShadow:{'glow':'0 0 15px rgba(59, 130, 246, 0.5)','inner-lg':'inset 0 2px 4px 0 rgb(0 0 0 / 0.1)',},borderRadius:{'4xl':'2rem','5xl':'2.5rem',},transitionTimingFunction:{'bounce-in':'cubic-bezier(0.68, -0.55, 0.265, 1.55)',},}

四、方法三:@layer 指令

4.1 Base 层 — 全局基础样式

@tailwindbase;@layerbase{/* 全局字体平滑 */html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;}/* CSS 变量定义 */:root{--color-surface:#ffffff;--color-on-surface:#1a1a2e;--header-height:4rem;}.dark{--color-surface:#1a1a2e;--color-on-surface:#e2e8f0;}/* 重置或覆盖默认样式 */h1{@applytext-2xl font-bold tracking-tight;}h2{@applytext-xl font-semibold;}/* 焦点样式 */*:focus-visible{@applyoutline-2 outline-offset-2 outline-blue-500;}}

4.2 Components 层 — 组件级样式

@tailwindcomponents;@layercomponents{/* 使用 @apply 聚合 */.btn{@applyinline-flex items-center justify-center rounded-md px-4 py-2 text-sm font-medium transition-colorsfocus-visible:outline-nonefocus-visible:ring-2focus-visible:ring-offset-2disabled:pointer-events-nonedisabled:opacity-50;}.btn-primary{@applybtn bg-blue-600 text-whitehover:bg-blue-700focus-visible:ring-blue-500;}/* 也可以写原生 CSS */.input-field{@applyw-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm transition-colors;}.input-field:focus{@applyborder-blue-500 ring-1 ring-blue-500 outline-none;}/* 响应式组件 */.container-narrow{@applymx-auto w-full px-4sm:px-6lg:max-w-3xl;}}

4.3 Utilities 层 — 自定义工具类

@tailwindutilities;@layerutilities{/* 自定义工具类 */.text-balance{text-wrap:balance;}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}}.line-clamp-4{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:4;}}

Layer 优先级

base < components < utilities < 无 layer 的样式
  • utilities层优先级最高,可以覆盖components
  • 不在@layer中的样式优先级最高(慎用)

五、方法四:Plugin 插件

5.1 内联插件

// tailwind.config.jsconstplugin=require('tailwindcss/plugin');module.exports={plugins:[// 添加自定义工具类plugin(function({addUtilities,theme}){constnewUtilities={'.text-shadow':{textShadow:'0 2px 4px rgba(0,0,0,0.1)',},'.text-shadow-lg':{textShadow:'0 4px 8px rgba(0,0,0,0.15)',},'.text-shadow-none':{textShadow:'none',},};addUtilities(newUtilities);}),// 添加自定义组件plugin(function({addComponents,theme}){addComponents({'.card':{backgroundColor:theme('colors.white'),borderRadius:theme('borderRadius.xl'),padding:theme('spacing.6'),boxShadow:theme('boxShadow.lg'),border:`1px solid${theme('colors.gray.200')}`,},'.card-compact':{padding:theme('spacing.4'),},});}),// 添加基础样式plugin(function({addBase,theme}){addBase({'h1':{fontSize:theme('fontSize.2xl')},'h2':{fontSize:theme('fontSize.xl')},});}),// 动态生成工具类plugin(function({addUtilities,e,theme}){constgradients=theme('gradients',{});Object.entries(gradients).forEach(([name,value])=>{addUtilities({[`.bg-gradient-${e(name)}`]:{backgroundImage:value,},});});}),],theme:{gradients:{'blue':'linear-gradient(to right, #3b82f6, #8b5cf6)','green':'linear-gradient(to right, #10b981, #3b82f6)','sunset':'linear-gradient(to right, #f97316, #ec4899)',},},};

5.2 独立插件包

// my-tailwind-plugin/index.jsconstplugin=require('tailwindcss/plugin');module.exports=plugin.withOptions(function(options={}){returnfunction({addUtilities,theme}){constprefix=options.prefix??'my';addUtilities({[`.${prefix}-text-gradient`]:{backgroundImage:`var(--gradient,${theme('gradients.blue','linear-gradient(to right, #3b82f6, #8b5cf6)')})`,WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',},});};},function(options){return{theme:{gradients:{blue:'linear-gradient(to right, #3b82f6, #8b5cf6)',sunset:'linear-gradient(to right, #f97316, #ec4899)',},},};});
// 使用module.exports={plugins:[require('./my-tailwind-plugin')({prefix:'app'}),],};

六、方法五:CSS 变量 + Tailwind 联动

6.1 定义 CSS 变量

@layerbase{:root{--color-background:#ffffff;--color-foreground:#171717;--color-primary:#2563eb;--color-muted:#f5f5f5;--radius:0.5rem;}.dark{--color-background:#0a0a0a;--color-foreground:#ededed;--color-primary:#3b82f6;--color-muted:#262626;}}

6.2 在 Tailwind 配置中引用

module.exports={theme:{extend:{colors:{background:'var(--color-background)',foreground:'var(--color-foreground)',primary:'var(--color-primary)',muted:'var(--color-muted)',},borderRadius:{DEFAULT:'var(--radius)',},},},};
<divclass="bg-background text-foreground"><buttonclass="bg-primary text-white rounded-md">按钮</button><divclass="bg-muted p-4">静音区域</div></div>

6.3 运行时切换主题

// 切换暗色模式document.documentElement.classList.toggle('dark');// 动态修改变量(如用户自定义主题色)document.documentElement.style.setProperty('--color-primary','#ec4899');

七、方法六:Important 修饰符与优先级控制

<!-- ! 前缀强制 important --><pclass="!text-red-500 font-bold"><!-- 生成: color: #ef4444 !important; -->
// 全局开启 important(避免与第三方 CSS 冲突)module.exports={important:true,// 所有工具类都加 !important// 或指定选择器(推荐,避免与第三方库冲突)important:'#app',};
/* 生成结果 */#app .text-red-500{color:#ef4444;}

八、完整配置示例

// tailwind.config.jsconstplugin=require('tailwindcss/plugin');module.exports={content:['./src/**/*.{html,js,jsx,ts,tsx,vue}'],important:'#app',theme:{extend:{// 颜色系统colors:{brand:{50:'#eff6ff',500:'#3b82f6',600:'#2563eb',700:'#1d4ed8',},surface:'var(--color-surface)',},// 字体fontFamily:{sans:['Inter','system-ui','sans-serif'],mono:['JetBrains Mono','monospace'],},// 动画keyframes:{'fade-in':{'0%':{opacity:'0'},'100%':{opacity:'1'},},},animation:{'fade-in':'fade-in 0.3s ease-out',},// 自定义间距spacing:{'18':'4.5rem',},},},plugins:[// 自定义工具类插件plugin(function({addUtilities}){addUtilities({'.text-balance':{textWrap:'balance'},'.scrollbar-hide':{'-ms-overflow-style':'none','scrollbar-width':'none','&::-webkit-scrollbar':{display:'none'},},});}),],};

九、决策速查表

需求推荐方案示例
一次性特殊值Arbitrary Valuestop-[17px]
设计系统级颜色/间距theme.extendcolors.brand.500
全局基础样式@layer base字体平滑、CSS 变量
组件级样式聚合@layer components+@apply.btn-primary
自定义工具类@layer utilities或 Plugin.text-balance
动态主题切换CSS 变量 +theme.extendvar(--color-primary)
可复用插件Plugin 包addUtilities/addComponents
覆盖第三方样式important!前缀!text-red-500

核心原则

  1. Arbitrary Values 用于一次性— 出现 2 次以上就应提取到配置
  2. extend优先于覆盖— 保留 Tailwind 默认值
  3. CSS 变量实现动态主题— 配合theme.extend双向联动
  4. @layer控制优先级— base < components < utilities
  5. Plugin 用于跨项目复用— 单项目用@layer即可
http://www.jsqmd.com/news/701763/

相关文章:

  • VSCode 2026嵌入式调试适配全攻略:5步完成J-Link/OpenOCD/PyOCD多协议零配置接入
  • 量子计算基础:Hadamard门与CNOT门的原理与应用
  • 从CVE-2023-XXXX到2026零容忍机制:17个真实工业级漏洞如何被新规范提前封堵(含NASA/JPL内部审计案例节选)
  • BGE-M3新手教程:如何用语义分析提升你的AI应用效果
  • C++ MCP网关TCO优化黄金公式:1行编译器flag + 2个零拷贝改造 + 3次ABI精简 = 年省¥287万(某金融客户实证)
  • 小白也能搞定:SenseVoice-Small语音识别镜像完整使用教程
  • Tailwind CSS 指令与函数
  • 从constexpr if到compile-time reflection,C++元编程范式革命,你还在手写type_list?
  • 无需代码!用HeyGem WebUI版快速搭建企业数字人视频生产线
  • PyTorch单层神经网络实现与调试指南
  • nli-MiniLM2-L6-H768多场景落地:已集成至3个开源RAG框架默认NLI组件
  • bge-large-zh-v1.5快速部署:小白友好的Embedding服务搭建
  • NovelClaw:基于动态记忆与可观测架构的AI长篇叙事工作台
  • 微信聊天记录完整导出终极指南:3步实现永久保存与智能管理
  • VSCode协作权限漏洞扫描工具上线(v2026.3):3分钟定位未授权Git提交、终端越权执行与Debug会话劫持风险
  • Phi-3-mini-4k-instruct-gguf惊艳案例:用自然语言描述生成完整可运行Python代码
  • 【VSCode 2026权限控制黄金标准】:为什么头部科技公司已禁用“共享工作区默认读写”?4类角色权限矩阵表免费领取
  • S2-Pro模型部署避坑指南:从Windows到Linux的常见环境问题解决
  • 3步解密网页视频下载:VideoDownloadHelper智能解析实战指南
  • TEdit深度解析:泰拉瑞亚地图编辑器的技术实现与应用实践
  • 现在不重构你的C++ MCP网关,Q4流量洪峰会触发第7类内核OOM Killer(附/proc/sys/net/core/bpf_jit_enable实测拐点曲线)
  • IndexTTS2 V23镜像效果展示:多情感语音生成案例,听感真实自然
  • 别再重装VSCode了!2026内存优化终极 checklist:12项配置项+8个进程级kill命令+1个自研memory-guard插件
  • 流体天线阵列与空中计算技术的联合优化实践
  • LangGraph 状态管理深度解析:Reducer、Annotation、Channel 是什么关系
  • Python描述性统计分析在机器学习数据预处理中的应用
  • Qianfan-OCR辅助数据库课程设计:实现纸质调查问卷的数字化与分析
  • 基于Qwen3-0.6B-FP8的数据库智能助手:自然语言转SQL实战
  • 异常检测技术:隔离森林与核密度估计实战指南
  • 2026若尔盖核心景点周边景区运营技术全解析:若尔盖景区推荐/若尔盖景区景点/若尔盖景区游玩攻略/若尔盖景点一日游路线/选择指南 - 优质品牌商家