Tailwind CSS 自定义样式
Tailwind CSS 自定义样式学习笔记一、自定义样式的层次结构┌──────────────────────────────────────────────────────┐ │ tailwind.config.js → 设计系统 Token颜色/间距/字号 │ │ layer base → 全局基础样式重置 │ │ layer components → 组件级自定义类 │ │ layer utilities → 自定义工具类 │ │ layer 外部 → 第三方/覆盖样式 │ │ arbitrary values → 一次性行内自定义值 │ └──────────────────────────────────────────────────────┘二、方法一Arbitrary Values任意值无需修改配置直接在类名中使用方括号语法写入任意 CSS 值。基本语法!-- 间距 --divclassmt-[17px] w-[calc(100%-3rem)] p-[2.5rem]!-- 颜色 --spanclasstext-[#1da1f2] bg-[rgb(59,130,246,0.5)]!-- 字体 --pclasstext-[22px] leading-[27px] font-[500] tracking-[0.01em]!-- 动画 --divclassanimate-[spin_1.5s_linear_infinite]!-- 背景图 --divclassbg-[url(/hero-pattern.png)] bg-[size:100px_100px]任意变体Arbitrary Variants!-- 任意媒体查询 --divclass[supports(display:grid)]:grid!-- 任意选择器 --divclass[:nth-child(3)]:underlinedivclass[::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-950brand:{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),},},},},};buttonclassbg-brand-500 text-white hover:bg-brand-600品牌按钮/buttondivclassbg-surface text-on-surface主题卡片/div2.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}],},}h1classfont-display text-2xl标题/h1codeclassfont-mono text-xxs代码/code2.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,},}divclassanimate-fade-in淡入效果/divdivclassanimate-slide-in-right右侧滑入/div2.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.jsconstpluginrequire(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}){constgradientstheme(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.jsconstpluginrequire(tailwindcss/plugin);module.exportsplugin.withOptions(function(options{}){returnfunction({addUtilities,theme}){constprefixoptions.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),},},},};divclassbg-background text-foregroundbuttonclassbg-primary text-white rounded-md按钮/buttondivclassbg-muted p-4静音区域/div/div6.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.jsconstpluginrequire(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 componentsapply.btn-primary自定义工具类layer utilities或 Plugin.text-balance动态主题切换CSS 变量 theme.extendvar(--color-primary)可复用插件Plugin 包addUtilities/addComponents覆盖第三方样式important或!前缀!text-red-500核心原则Arbitrary Values 用于一次性— 出现 2 次以上就应提取到配置extend优先于覆盖— 保留 Tailwind 默认值CSS 变量实现动态主题— 配合theme.extend双向联动layer控制优先级— base components utilitiesPlugin 用于跨项目复用— 单项目用layer即可
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2555193.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!