Tailwin CSS 基础下篇

news/2025/2/6 23:10:17/文章来源:https://www.cnblogs.com/AJun816/p/18701852

Tailwin CSS 进阶·上篇

方便自己查看,仅做摘录,非原创。

原文链接

听说你还不会 Tailwind CSS(基础·上篇)Tailwind CSS 的基础使用:从宽度高度开始逐步展现 Tai - 掘金 (juejin.cn)

听说你还不会 Tailwind CSS(基础·中篇)Tailwind CSS 的基础使用:包含伪类、伪元素、flex 和 - 掘金 (juejin.cn)

听说你还不会 Tailwind CSS(基础·下篇)这是 Tailwind CSS 的基础使用的终篇:包括形变、过渡效果 - 掘金 (juejin.cn)

听说你还不会 Tailwind CSS(进阶·上篇)Tailwind CSS 的进阶使用(上篇):如何复用样式以及自定义 - 掘金 (juejin.cn)

听说你还不会 Tailwind CSS(进阶·下篇)Tailwind CSS 的进阶使用(下篇):配置项讲解。样式的覆盖 - 掘金 (juejin.cn)

听说你还不会 Tailwind CSS(响应式篇)讲解传统响应式和 TailwindCSS 中的响应式,有了 Tailw - 掘金 (juejin.cn)

Tailwind CSS | Pure Admin 保姆级文档 (pure-admin.github.io)

前言

基础篇:

  • 听说你还不会 Tailwind CSS(基础·上篇)
  • 听说你还不会 Tailwind CSS(基础·中篇)
  • 听说你还不会 Tailwind CSS(基础·下篇)

进阶篇:

  • 听说你还不会 Tailwind CSS(进阶·上篇)

经过初始化后,在根目录下有一个 tailwind.config.ts 文件:

ts 代码解读复制代码import type { Config } from "tailwindcss";const config: Config = {content: ["./pages/**/*.{js,ts,jsx,tsx,mdx}","./components/**/*.{js,ts,jsx,tsx,mdx}","./app/**/*.{js,ts,jsx,tsx,mdx}",],theme: {extend: {backgroundImage: {"gradient-radial": "radial-gradient(var(--tw-gradient-stops))","gradient-conic":"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",},},},plugins: [],
};
export default config;

上面就是 Tailwind CSS 的配置文件,这篇文章主要讲解 theme 配置项,利用它来实现样式的扩展。

content

content 配置项将会接收一个数组,表示应用 Tailwind CSS 的文件范围:

  • "./pages/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./pages 目录下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件
  • "./components/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./components 下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件
  • "./app/**/*.{js,ts,jsx,tsx,mdx}" 👉 ./app 下无限级别子目录中的所有以 js、ts、jsx、tsx、mdx 结尾的文件

其中,**/* 表示该目录下的无限级别子目录。

theme

theme 在之前已经遇到过,使用 theme() 函数可以获取 Tailwind 默认的样式变量,比如:颜色搭配、字体、边框、响应式断点等等内容。

覆盖原样式

默认情况下,初始化时就会生成默认的配置内容,具体看这里。

如果说要覆盖掉默认的样式,比如,覆盖掉默认颜色:

ts 代码解读复制代码import type { Config } from 'tailwindcss';const config: Config = {// ...theme: {colors: {blue: '#1fb6ff',purple: '#7e5bef',pink: '#ff49db',orange: '#ff7849',green: '#13ce66',yellow: '#ffc82c','gray-dark': '#273444',gray: '#8492a6','gray-light': '#d3dce6',},},
};
export default config;

colors 用于定义默认颜色,因此想要使用的颜色应该写在那里。使用看看:

html 代码解读复制代码<pre class="text-blue">blue: &apos;#1fb6ff&apos;</pre>
<pre class="text-purple">purple: &apos;#7e5bef&apos;</pre>
<pre class="text-pink">purple: &apos;#ff49db&apos;</pre>

颜色覆盖.png

上面代码中的 ' 表示 HTML 中的 '

由于覆盖了 colors 对象的配置,原来的默认颜色就不起作用了,比如下面的 red-200 就不起作用:

html代码解读
复制代码<p class="text-red-200">text-red-200 没有效果</p>

原来的颜色不再生效.png

尽管 colors 的值被覆盖了,但是其他的配置不受影响,比如 spacing,它们继续继承默认值。

扩展原样式

更多的时候,我们希望使用 Tailwind 的便利,同时添加更多的选择。比如,想要追加一些新的颜色,那么就在 extend 对象中添加:

ts 代码解读复制代码import type { Config } from 'tailwindcss';const config: Config = {// ...theme: {// ...extend: {colors: {'primary-dark': '#1f2937','primary-light': '#f3f4f6','secondary-dark': '#1f2937','secondary-light': '#f3f4f6',},},},
};
export default config;

然后使用这些新增的颜色:

html 代码解读复制代码<p class="text-primary-dark">primary-dark</p>
<p class="text-primary-light bg-primary-dark">primary-dark</p>
<p class="text-secondary-dark">primary-dark</p>
<p class="text-secondary-light bg-secondary-dark">primary-dark</p>

扩展颜色.png

可扩展的关键词

除了 colors,之前的文章中提到的 spacing,又或者是控制响应式 screens,也都可以被覆盖或扩展。下面是一张完整的样式声明配置及其对应关系的描述表格:

关键词 描述
accentColor Values for the accent-color property
animation Values for the animation property
aria Values for the aria property
aspectRatio Values for the aspect-ratio property
backdropBlur Values for the backdropBlur plugin
backdropBrightness Values for the backdropBrightness plugin
backdropContrast Values for the backdropContrast plugin
backdropGrayscale Values for the backdropGrayscale plugin
backdropHueRotate Values for the backdropHueRotate plugin
backdropInvert Values for the backdropInvert plugin
backdropOpacity Values for the backdropOpacity plugin
backdropSaturate Values for the backdropSaturate plugin
backdropSepia Values for the backdropSepia plugin
backgroundColor Values for the background-color property
backgroundImage Values for the background-image property
backgroundOpacity Values for the background-opacity property
backgroundPosition Values for the background-position property
backgroundSize Values for the background-size property
blur Values for the blur plugin
borderColor Values for the border-color property
borderOpacity Values for the borderOpacity plugin
borderRadius Values for the border-radius property
borderSpacing Values for the border-spacing property
borderWidth Values for the borderWidth plugin
boxShadow Values for the box-shadow property
boxShadowColor Values for the boxShadowColor plugin
brightness Values for the brightness plugin
caretColor Values for the caret-color property
colors Your project's color palette
columns Values for the columns property
container Configuration for the container plugin
content Values for the content property
contrast Values for the contrast plugin
cursor Values for the cursor property
divideColor Values for the divideColor plugin
divideOpacity Values for the divideOpacity plugin
divideWidth Values for the divideWidth plugin
dropShadow Values for the dropShadow plugin
fill Values for the fill plugin
flex Values for the flex property
flexBasis Values for the flex-basis property
flexGrow Values for the flex-grow property
flexShrink Values for the flex-shrink property
fontFamily Values for the font-family property
fontSize Values for the font-size property
fontWeight Values for the font-weight property
gap Values for the gap property
gradientColorStops Values for the gradientColorStops plugin
gradientColorStopPositions Values for the gradient-color-stop-positions property
grayscale Values for the grayscale plugin
gridAutoColumns Values for the grid-auto-columns property
gridAutoRows Values for the grid-auto-rows property
gridColumn Values for the grid-column property
gridColumnEnd Values for the grid-column-end property
gridColumnStart Values for the grid-column-start property
gridRow Values for the grid-row property
gridRowEnd Values for the grid-row-end property
gridRowStart Values for the grid-row-start property
gridTemplateColumns Values for the grid-template-columns property
gridTemplateRows Values for the grid-template-rows property
height Values for the height property
hueRotate Values for the hueRotate plugin
inset Values for the top, right, bottom, and left properties
invert Values for the invert plugin
keyframes Keyframe values used in the animation plugin
letterSpacing Values for the letter-spacing property
lineHeight Values for the line-height property
listStyleType Values for the list-style-type property
listStyleImage Values for the list-style-image property
margin Values for the margin property
lineClamp Values for the line-clamp property
maxHeight Values for the max-height property
maxWidth Values for the max-width property
minHeight Values for the min-height property
minWidth Values for the min-width property
objectPosition Values for the object-position property
opacity Values for the opacity property
order Values for the order property
outlineColor Values for the outline-color property
outlineOffset Values for the outline-offset property
outlineWidth Values for the outline-width property
padding Values for the padding property
placeholderColor Values for the placeholderColor plugin
placeholderOpacity Values for the placeholderOpacity plugin
ringColor Values for the ringColor plugin
ringOffsetColor Values for the ringOffsetColor plugin
ringOffsetWidth Values for the ringOffsetWidth plugin
ringOpacity Values for the ringOpacity plugin
ringWidth Values for the ringWidth plugin
rotate Values for the rotate plugin
saturate Values for the saturate plugin
scale Values for the scale plugin
screens Your project's responsive breakpoints
scrollMargin Values for the scroll-margin property
scrollPadding Values for the scroll-padding property
sepia Values for the sepia plugin
skew Values for the skew plugin
space Values for the space plugin
spacing Your project's spacing scale
stroke Values for the stroke property
strokeWidth Values for the stroke-width property
supports Values for the supports property
data Values for the data property
textColor Values for the text-color property
textDecorationColor Values for the text-decoration-color property
textDecorationThickness Values for the text-decoration-thickness property
textIndent Values for the text-indent property
textOpacity Values for the textOpacity plugin
textUnderlineOffset Values for the text-underline-offset property
transformOrigin Values for the transform-origin property
transitionDelay Values for the transition-delay property
transitionDuration Values for the transition-duration property
transitionProperty Values for the transition-property property
transitionTimingFunction Values for the transition-timing-function property
translate Values for the translate plugin
size Values for the size property
width Values for the width property
willChange Values for the will-change property
zIndex Values for the z-index property

预处理器的使用

在上一篇中有朋友评论:

网友评论.png

postcss-nesting

官方推荐的 postcss-nesting 插件可以满足嵌套的需求。首先安装依赖:

bash代码解读
复制代码npm install -D postcss-nesting

然后放进 postcss 处理器配置中(postcss.config.mjs):

js 代码解读复制代码/** @type {import('postcss-load-config').Config} */
const config = {plugins: {'tailwindcss/nesting': 'postcss-nesting',tailwindcss: {},},
};export default config;

现在使用一下子,在 global.css 中添加以下代码:

css 代码解读复制代码/* ... */@layer utilities {.container {@apply w-[1280px] mx-auto;span {@apply text-lg text-blue;}}
}

.container 用于控制容器内容居中,span 元素嵌套在其中。

html 代码解读复制代码<div class="container bg-gray-light"><p>Lorem ipsum <span>dolor</span> sit amet, consectetur adipisicing elit.Sit accusamus incidunt, minima eligendi delectus sint facere cum,placeat dolorum rem debitis <span>doloribus</span> dolore nesciuntratione laudantium <span>doloribusstop</span>enim error architectoodio!</p>
</div>

postcss-nesting 使用效果.png

实测有效。

就是想用 Sass

笔者头铁,笔者就是想用 Sass!

让人头大.png

也不是不行,不过需要知道一件事:预处理器(Sass 之类的)和 Tailwind CSS 是在不同的阶段处理的。预处理器首先处理其输入文件并生成 CSS,然后 Tailwind CSS 和 PostCSS 在预处理器生成的 CSS 上继续处理。

也就是说,不能把 Tailwind 的 theme() 函数的输出传给一个 Sass 的颜色函数,比如:

css 代码解读复制代码.error {background-color: darken(theme('colors.red.500'), 10%);
}
.btn:hover {background-color: light(theme('colors.red.500'), 10%);
}

darken($color, $amount)lighten($color, $amount) 就是 Sass 中的颜色函数。由于 Sass 在 Tailwind 之前运行,还未生成 CSS,因此 theme() 并不可用。

以 React 和 Sass 为例,有 Demo.module.scss 如下:

css 代码解读复制代码.container {@apply w-[1280px] mx-auto;span {@apply text-lg text-blue;}
}.title {// @apply text-4xl font-bold;font-size: 36px;line-height: 40px;font-weight: bold;
}.success {background-color: theme('colors.green');
}

引入到组件中使用:

typescript 代码解读复制代码import styles from './Demo.module.scss';export default function Page() {return (<div><div className={styles.container}><h1 className={styles.title}>hello</h1><p>Lorem ipsum <span>dolor</span> sit amet, consectetur adipisicing elit.Sit accusamus incidunt, minima eligendi delectus sint facere cum,placeat dolorum rem debitis <span>doloribus</span> dolore nesciuntratione laudantium <span>doloribusstop</span>enim error architectoodio!</p><p className={styles.success}>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corporis,maiores eos. Aliquam reiciendis, totam eos deserunt earum, quos velitquo magnam temporibus quaerat voluptate expedita nostrum eligendiaspernatur fuga harum!</p></div></div>);
}

使用 Sass.png

总结

除此以外, Tailwind 还有更多的配置项,如 pluginspresetsprefix 等等,这些内容不需要特别去看,只要知道它们可以做什么,用到时检索即可。下面用一句话分别概括:

  • plugins:添加自定义插件以扩展 Tailwind 的功能。
  • presets:自定义预设样式,多个项目可共享一套配置。
  • prefix:为所有 Tailwind 生成的 utilities 类添加前缀,帮助避免命名冲突。
  • important:配置所有 utilities 类标记为!important,确保它们优先应用。
  • corePlugins:禁用某些不想用的样式,减小 CSS 体积。

总结一下,想要覆盖样式使用 theme.key 去覆盖,想要扩展更多则使用 theme.extend.key ,可用的 key 在 3.3 节中;另外使用嵌套语法,还是推荐 postcss-nesting 而不是直接使用 Sass 等预处理器,一方面它的构建速度更快,另一方面仅通过 @tailwind、@apply、theme() 等 Tailwind 关键词的组合就能达到相同的效果。反之,使用预处理器就要考虑语法、执行顺序等等情况,变相增加了开发者的心智负担。

以上就是进阶篇的所有内容,掌握了这些在一般的项目开发已经完全够用了,下篇将讲解响应式相关内容,让你用一套代码搞定多端的 UI 显示。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/879865.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ctfshow密码学wp

打hgame打傻了来洗洗脑子( 1、密码学签到2、 jsfuck扔控制台3、 aaencode颜文字4、 ctfrsatoolsfrom Crypto.Util.number import * from gmpy2 import * p=447685307 q=2037 e=17 phi=(p-1)*(q-1) d=inverse(e,phi) print(d) 5、 交intimport gmpy2,libnum f…

异动拉升之量子图形矩阵

一.量子图形矩阵通过异动拉升算法检测出异动拉升的股票之后,需要图形化显示股票分时曲线,帮助观察股票异动之后的走势,量子图形矩阵的功能就是将异动拉升的股票,按照冠绝榜中的排序,从上到下依次展示在图形矩阵中,可以选择4,9,16个窗口,在窗口没有锁住的情况下,新出现…

MySQL主从复制 —— 作用、原理、数据一致性,异步复制、半同步复制、组复制

MySQL主从复制 作用、原理—主库线程、I/O线程、SQL线程;主从同步要求,主从延迟原因及解决方案;数据一致性,异步复制、半同步复制、组复制文章目录 一、作用 二、原理 三、同步数据一致性3.1 主从同步要求3.2 主从延迟原因、直接表现3.3 减少主从延迟的方案3.4 数据一致性…

2024人工智能AI+制造业应用落地研究报告汇总PDF洞察(附原数据表)

原文链接: https://tecdat.cn/?p=39068 本报告合集洞察深入剖析当前技术应用的现状,关键技术 创新方向,以及行业应用的具体情况,通过制造业具体场景的典型 案例揭示人工智能如何助力制造业研发设计、生产制造、运营管理 和产品服务的全流程智能化升级。在此基础上对制造业…

中国综合算力指数(2024年)报告汇总PDF洞察(附原数据表)

原文链接: https://tecdat.cn/?p=39061 在全球算力因数字化技术发展而竞争加剧,我国积极推进算力发展并将综合算力作为数字经济核心驱动力的背景下,该报告对我国综合算力进行研究。 中国算力大会发布的《中国综合算力指数(2024年)报告》显示,我国算力结构调整,智算规模…

基于Java语言的开源能管平台才是最适合国内的额的能源管理平台

在"双碳"战略背景下,能源管理已成为政府、企业实现可持续发展的必经之路。面对市场上各类能源管理平台,为何基于Java语言的开源解决方案才是最佳选择?本文将为您揭晓答案,并向您推荐我公司自研的真正具备行业竞争力的开源平台——智碳EMS。 一、智碳EMS:企业能源…

Spring AI + DeepSeek:提升业务流程的智能推理利器

今天,我们将深入探讨如何利用DeepSeek来真正解决我们当前面临的一些问题。具体来说,今天我们仍然会将DeepSeek接入到Spring AI中进行利用。需要注意的是,虽然DeepSeek目前主要作为推理型助手存在,并不完全适合作为智能体的首选,但它仍然能够有效地融入并提升你的业务流程。…

铁路位移智能识别摄像机

铁路位移智能识别摄像机逐渐成为主流。这种设备能够通过高清镜头实时捕捉轨道状况,并利用图像处理技术进行精准分析,从而实现高效的数据收集与预警。铁路位移智能识别摄像机通常安装在关键路段,如桥梁、隧道及坡道等易发生位移的位置。其核心功能是通过实时拍摄轨道,并结合…

边坡智能识别摄像机

边坡智能识别摄像机逐渐成为主流。这种设备能够通过高清镜头实时捕捉边坡状况,并利用图像处理技术进行精准分析,从而实现高效的数据收集与预警。边坡智能识别摄像机通常安装在关键区域,如陡峭山体、施工现场及易受影响的位置。其核心功能是通过实时拍摄边坡,并结合深度学习…

Centos7.9版本安装collectd并开启写入rrd文件功能

Centos7.9版本安装collectd并开启写入rrd文件功能@目录一、背景介绍二、为什么用这个三、安装Collectd3.1 尝试docker安装3.2尝试执行linux命令一步一步安装安装collectd表示该插件开发完毕,可以使用(需要下载相应的插件包,然后取消注释)表示该插件还未完成,无法使用。设置…

15年测试经验沉淀:这些“软实力”让你少走10年弯路

在测试领域深耕近十五载,最近终于得些闲暇,遂撰写小文,分享工作中的些许心得与看法。此次,我来聊聊与 “测试技术” 虽无直接关联,却与个人成长密切相关的一些要点。 以下观点,有的源自他人教导,有的则是我个人感悟所得,欢迎大家一起来探讨。📝 博主首页 : 「码上生…

MySQL日志详解——日志分类、二进制日志bin log、回滚日志undo log、重做日志redo log

MySQL日志详解——日志分类、二进制日志bin log、回滚日志undo log、重做日志redo log、原理、写入过程;binlog与redolog区别、update语句的执行流程、两阶段提交、主从复制、三种日志的使用场景;查询日志、慢查询日志、错误日志等其他几类日志文章目录 一、前言1.1 MySQL体系…