在默认情况下,Tailwind对每个小的CSS类都进行了预定义,比如:text-lg对应的CSS属性为:
font-size: 1.125rem;
line-height: 1.75rem;
但有些时候,我们需要对这些属性进行重新定义。
创建包含所有选项的配置文件
我们可以先查看一下Tailwind中所有的样式定义。运行如下命令:
npx tailwindcss init --full
如果不想覆盖默认的配置文件,可以运行如下命令:
npx tailwindcss init tailwind-full.config.js --full
我们就能看到已经创建好的tailwind.config.js,其中包含了所有的默认CSS类。
在默认配置文件中定义了所有Tailwind中的类,比如:
theme: {
colors: {
gray: {
100: '#f7fafc',
200: '#edf2f4',
}
// ...
}
}
或者通过闭包的方式定义其他类,进而可以复用前面定义的colors:
backgroundColor: theme => theme('colors')
修改Tailwind默认样式
不推荐方式:增加自定义样式
不推荐这种方式,主要是因为以下方式会污染Tailwind的样式定义,进而会变得难以维护。以下只是为了演示如何添加样式。
可以看到创建的tailwind.config.js大约有1000行左右。这时就可以对现有样式进行修改或添加新样式,比如:增加一个自定义字体大小:lcodingxxl:
fontSize: {
lcodingxxl: ['7rem', { lineHeight: '1' }],
xs: ['0.75rem', { lineHeight: '1rem' }],
sm: ['0.875rem', { lineHeight: '1.25rem' }],
base: ['1rem', { lineHeight: '1.5rem' }],
lg: ['1.125rem', { lineHeight: '1.75rem' }],
xl: ['1.25rem', { lineHeight: '1.75rem' }],
'2xl': ['1.5rem', { lineHeight: '2rem' }],
'3xl': ['1.875rem', { lineHeight: '2.25rem' }],
'4xl': ['2.25rem', { lineHeight: '2.5rem' }],
'5xl': ['3rem', { lineHeight: '1' }],
'6xl': ['3.75rem', { lineHeight: '1' }],
'7xl': ['4.5rem', { lineHeight: '1' }],
'8xl': ['6rem', { lineHeight: '1' }],
'9xl': ['8rem', { lineHeight: '1' }],
},
然后需要重新编译CSS:
npm run buildcss
此时就可以在HTML中使用自定义类了:
<h1 class="font-bold uppercase text-lcodingxxl text-blue-900">Test lcoding font size</h1>
推荐方式:单独定义额外样式
首先恢复默认的精简版tailwind.confg.js:
module.exports = {
content: [
"./**/*.html",
],
theme: {
extend: {},
},
plugins: [],
}
然后在extend中添加额外配置:
extend: {
colors: {
primary: '#E86A64',
secondary: {
100: '#DF2225',
200: '#978283',
},
},
fontSize: {
lcodingxxl: ['7rem', { lineHeight: '1' }],
},
},
那么后面在html中就可以这样使用这些样式类了:
<p class="text-primary">
</p>
<div class="bg-secondary-100">
</div>
需要注意的是,只有在HTML中开始使用这些自定义样式之后,Tailwind在重新编译的时候才能生成对应的标准CSS样式。比如针对上面的样式text-primary以及bg-secondary-100,Tailwind编译之后才会生成对应的标准样式:
.text-primary {
--tw-text-opacity: 1;
color: rgb(255 99 99 / var(--tw-text-opacity));
}
.bg-secondary-100 {
--tw-bg-opacity: 1;
background-color: rgb(226 226 213 / var(--tw-bg-opacity));
}
使用自定义字体
首先访问Google Font并选择自己喜欢的字体,比如Roboto:https://fonts.google.com/specimen/Roboto
选择所有样式后选择”@import”将会得到如下引用方式:
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
</style>
将这段代码复制到src/css/styles.pcss的最前面:
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
修改Tailwind.config.js:
extend: {
// ...
fontFamily: {
lcoding: ['Roboto'],
},
// ...
},
重新编译CSS之后就可以使用自定义字体了:
<body class="font-lcoding">