Reason & Foreword
- If you have not heard of tailwindcss , please
return
first, this article does not talk about what and how to usetailwindcss
, but how to use it gracefully. If you've heard of it, read on and consider using
tailwindcss
, because after reading:- Development: It may save you and even your front-end team a lot of time to write styles , and it can also greatly improve your or your project development experience
- Production: The proportion of style code in the package size of your project will suddenly drop sharply and then tend to remain unchanged .
do you really need a css preprocessor
Maybe when most students develop or maintain a project, they should use css
preprocessing languages such as scss
, less
, stylus
, etc., and even some single projects use multiple preprocessing languages, which may be In order to use variable , presumably to multiplex style convenient it may be to write some function help us to do some deal with some style values, but most of the time we are to can write nested styles , In short, to improve our development efficiency, all this was so beautiful before tailwindcss
appeared, until we met tailwindcss
, you will find that you don't even need to configure stylelint
, because you may not need to write css
at all
How & Which Version
tailwindcss v2 vs v3
If your project needs to be compatible with IE
, please use the v2
version, if not, please decisively use the v3
version
Specifically how to use tailwindcss
in your project, please be sure to check the official website document v2 Chinese v3English , it is recommended to add based on postcss
Install the vscode plugin
If you decide to use tailwindcss
, install the official plug-in bradlc.vscode-tailwindcss
, which can provide hints, completions, and the ability to view the styles actually set
Configure your tailwind
If you have followed the documentation tutorial to create the tailwind.config.js
file, then we need to configure this file further
PC-side project
If your project is only for PC
web pages, maybe you only need to ask your design classmates what are some based design principles in your project, such as some theme colors , font sizes that will be used , Margin size inside and outside, gradient , Commonly used border fillet size, gradient , border width, gradient The basic principles of design, if you will use these basic principles, if you use these basic principles, negotiate with them. , the margin unit is generally set in multiples of 4px
...
colour
If the design students provide the theme colors in the project and have semantic names, such as semantic colors like success
, info
, warning
, we can configure our colors based on these, including but not limited to fonts, backgrounds , border, shadow color (you can use a class like text-success
to set the color directly after configuration), you can replace the variable function of the css
preprocessor
// tailwindcss v3
const colors = {
'success': '#654321',
'info': '#123456',
'warning': '#666666',
// ...
}
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
// ...
colors,
},
plugins: [],
}
// tailwindcss v2
const colors = {
'success': '#654321',
'info': '#123456',
'warning': '#666666',
// ...
}
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
// ...
textColor: colors,
backgroundColor: colors,
borderColor: colors,
},
plugins: [],
}
The settings of the v2
and v3
versions are slightly different, and the specific color of the v2
needs to be specified.
Spacing & Width & Line Height & Rounded Corners & Border Width
Because the default length-related configuration of tailwindcss
is based on rem
, and most of the time for the project on the PC
end, we fix a width and leave blanks on the left and right, so in most cases, the design draft will be within a fixed width, and the size of the element is wide and high. The margin units are all px
, so we need to make some specific configurations for the default to adapt to our project
const spacing = {
0: 0,
4: '4px',
8: '8px',
12: '12px',
// ... 项目中常用的都可以配置
}
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
// v3 & v2
spacing,
lineHeight: spacing,
borderWidth: spacing,
borderRadius: spacing,
},
plugins: [],
}
Mobile terminal adaptation solution
Possible for the mobile terminal adapter, is now popular viewport
program, they could still use some projects flexable
program, but we do not want to manually convert px
to rem
or vw
, although the community has a similar pxtorem
or pxtovw
this postcss
plug , but the solution to the problem is still not elegant enough, it may be because the maintenance of the plug-in is not active, the plug-in may not be easy to use, and it is not compatible with postcss8
( pxtovw
is talking about you 😤), since we all have tailwindcss
, let these The configuration has become simpler! If your design students provide common spacing schemes, such as multiples of 4px
or multiples of 6px
, and now suppose that the design drafts of design students are all 750px
, we can write two function methods based on this to handle the tasks of pxtorem
and pxtovw
, if you are the flexable
scheme, use pxToRem
, if it is the viewport
adaptation scheme, use pxToVmin
.
function pxToRem(variable) {
return `${variable / 75}rem`
}
function pxToVmin(variable) {
return `${variable / 7.5}vmin`
}
// flexable
const fontSize = {
12: pxToRem(12),
14: pxToRem(14),
16: pxToRem(16),
...
}, spacing = {
0: 0,
4: pxToRem(4),
8: pxToRem(8),
12: pxToRem(12),
...
}
// viewport
const fontSize = {
12: pxToVmin(12),
14: pxToVmin(14),
16: pxToVmin(16),
...
}, spacing = {
0: 0,
4: pxToVmin(4),
8: pxToVmin(8),
12: pxToVmin(12),
...
}
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
// ...
fontSize,
spacing
},
plugins: [],
}
Of course, the size of the rounded corners, the width of the border, etc. can be configured in this way. Is it more elegant than using a plug-in?
nested syntax
Some students may have a soft spot for the nested syntax of the css
preprocessor. Can it be in tailwindcss
? arrange!tailwindcss
have a plug-in called @ tailwindcss / nesting , based on some of the official website of the configuration , should be noted that the document is to give postcss
configuration tailwindcss/nesting
, in fact, need to configure @tailwindcss/nesting
, then you can based on css
provide the ability to nest, try it~
Truncate after fixed number of lines
Sometimes we need to write several lines of style code in order to write a text after the x
line and display ...
, so we usually define a scss
utility function like this
@mixin ellipsis($line: 1, $substract: 0) {
@if $line==1 {
white-space: nowrap;
text-overflow: ellipsis;
} @else {
display: -webkit-box;
-webkit-line-clamp: $line;
-webkit-box-orient: vertical;
}
width: 100% - $substract;
overflow: hidden;
}
tailwindcss
provides a proprietary plugin @tailwindcss/line-clamp for this special case, just install it and then import it in tailwind.config.js
in plugins
Install the plugin
npm install -D @tailwindcss/line-clamp
configure
// tailwind.config.js
module.exports = {
// ...
plugins: [
require('@tailwindcss/line-clamp'),
],
}
use
<div class="line-clamp-3">
<!-- ...3行后截断 -->
<div>
multiple themes
Maybe you are maintaining a project that needs to support multiple themes. There are multiple color schemes in different situations. tailwindcss
with css var
to achieve multi-theme color matching will be so simple that it will make you suffocate:
Configure the theme in your global css
file, assuming we have three different theme colors: success
, info
, warning
/* global base css */
@tailwind base;
@tailwind components;
@tailwind utilities;
// 默认主题
:root {
--success: 5 193 174;
--info: 51 163 238;
--warning: 237 214 18;
}
// 主题1的配色
.theme-1 {
--success: 36 195 102;
--info: 54 143 255;
--warning: 234 209 27;
}
// 主题2的配色
.theme-2 {
--success: 57 209 121;
--info: 0 186 255;
--warning: 234 209 27;
}
Then go to our tailwind.config.js
and change our color scheme
// 让我们的颜色支持透明度设置
function withOpacityValue(variable) {
return ({ opacityValue }) => {
return opacityValue === undefined
? `rgb(var(${variable}))`
: `rgb(var(${variable}) / ${opacityValue})`
}
}
const colors = {
success: withOpacityValue('--success'),
info: withOpacityValue('--info'),
warning: withOpacityValue('--warning'),
// ...
}
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
// ...
colors,
},
plugins: [require('@tailwindcss/line-clamp')],
}
Finally, set your theme according to different situations, and set the corresponding class
to the top-level element of the theme to be set, and all the internal color styles will be changed according to the specific theme!
<!-- 默认主题 -->
<div>
<!-- ... -->
</div>
<!-- 主题1 -->
<div class="theme-1">
<!-- ... -->
</div>
<!-- 主题2 -->
<div class="theme-2">
<!-- ... -->
</div>
some best practices
If the styles of some elements are particularly complex, resulting in the
html
code being very long and messy, how to optimize it? You cantailwindcss
a series of styles through a semantic class through the @apply directive provided by 0621605b38f9be<div class="complex-node">xxxx<div> // ... <style> .complex-node { @apply flex m-3 text-success rounded ....; } </style>
I have some styles that are globally common, such as buttons, some styles of cards, how do I maintain them? You can use the
tailwindcss
@layer instruction provided by to use the more general stylelayer
tocomponents
layer as a component-level style, so as to achieve the purpose of global reuse@layer components { .btn-blue { @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded; } }
My project is maintained by multiple people, how can I ensure that the atomized style class names have a reasonable order? For example, you like to write the width and height first and then write the positioning, but your colleague is contrary to you, how to formulate a specification?
tailwindcss
provides aprettier
plugin prettier-plugin-tailwindcss , you can standardize the formatting problems of different members writing style classes by installing the plugin and updating the configuration after savingnpm install -D prettier prettier-plugin-tailwindcss
Create a new configuration file
.prettierrc.json
type{}
and configure it according to the original configuration of your project. If it is a personal project, you can also configure it according to your personal preferences. Then install the pluginvscode
inesbenp.prettier-vscode
, and then open your settings to search forformat
, and set 0621605b39a8 toFormat On Paste
If allFormat On Save
are checked, you can automatically sort the order of your style classes after saving. The default sorting rules are based on the rules ofcss box model
from outside to inside:
margin
- border
- padding
- content
Summarize
I only talked about the capabilities of tailwindcss
for the parts that I usually use. In fact, there are still many capabilities that have not been mentioned, such as some styles for printing pages provided by v3
, hover
, active
, some settings such as pseudo-classes, In fact, it is relatively simple, just look at the official documentation when using it. Some friends may also complain about tailwindcss
There are many basic class names that need to be remembered, but in fact, there are not many, practice makes perfect, they are all things once and for all. If you also have a good configuration scheme or best practice, you can also tell me in the comment area. Finally, if it is useful, please like it. If you like it, please pay attention. I am Senar
(the same name as the official account), thank you!
Past content
Basic productivity literacy for front-end development (updated irregularly later)
Dear frontend developers, the time is ripe, let's start using pnpm
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。