Cause & Preface

  • If you haven’t heard of ittailwindcss, pleasereturn, not discussed in this papertailwindcssWhat is how to use, but how to use gracefully.
  • If you’ve heard of it, read on and consider using ittailwindcss, because after watching:
    • Development: It can save you and your front-end team a lot of time writing styles, and it can make a big difference to you and your project development experience
    • Productively: The percentage of style code in the volume of packages your project produces will suddenly plummet and then plateau.

Do you really need a CSS preprocessor

Most students probably use SCSS, LESS, stylus when developing or maintaining a project. CSS pretreatment such as language, and even some individual projects used in a variety of pretreatment of language, may be in order to use the variable, possibly to reuse pattern is convenient, can also be convenient to write some functions we do some processing on some style value, but most of the time we can write to nested pattern, in short, in order to improve the efficiency of our development, All this was great until tailwindCSS came along and you found that you didn’t even need to configure stylelint because you probably didn’t have to write CSS at all

How & Which Version

tailwindcss v2 vs v3

If your project needs to be compatible with IE, use VERSION V2. If not, use version V3

For details on how to use tailwindcss in your project, please check the official website document v2 Chinese v3English, recommend to add it based on postcss

Install the vscode plug-in

If you decide to use tailwindCSS, install bradlc.vscode- TailwindCSS, an official plug-in that provides hints, completion, and the ability to see the actual styles set

Configure your tailwind

If you have already created the tailwind.config.js file following the tutorial, it is time to further configure this file

PC project

If your project is only for PC web, maybe you just need to ask you for your design students project what are some of the basic design principles, such as the use of some theme colors, font size, margin size, both inside and outside gradient, gradient, commonly used frame size of fillet, gradient, border width, gradient, if it were not for the principle, design students Just negotiate some basic rules, like what colors to use, and margins are set in multiples of 4px.

color

If the designer provided a theme color for the project and had semantic names such as success, info, and warning, we could configure our colors based on these. Including but not limited to font, background, border, shadow color (after the configuration can be directly used to set the color of the text-success class), can replace the CSS preprocessor variable function

// 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: [],}Copy the code

The Settings of V2 and V3 are slightly different. The specific color of V2 needs to be specified.

Spacing & Width & Height & Line height & Rounded corners & border width

Since the default length of tailwindCSS is rem based, and most PC projects are fixed with a fixed width and left and right white space, most of the design will be within a fixed width, element size, width and height margin unit is px. So we need to do some specific configuration on the default to fit our project

const spacing = {
  0: 0.4: '4px'.8: '8px'.12: '12px'./ /... All commonly used items in the project can be configured
}
module.exports = {
  content: ['./index.html'.'./src/**/*.{vue,js,ts,jsx,tsx}'].theme: {
    // v3 & v2
    spacing,
    lineHeight: spacing,
    borderWidth: spacing,
    borderRadius: spacing,
  },
  plugins: [],}Copy the code

Mobile terminal adaptation scheme

Maybe viewPort is the most popular option for mobile, maybe some projects are still using Flexable, but we don’t want to manually convert PX to REM or VW, although there are postCSS plug-ins like PxtoREM or PxtoVW. But the solution to the problem is still not elegant, maybe because the plugin maintenance is not active, maybe the plugin is not working well, not compatible with PostcSS8 (pxtoVW is talking about you 😤), now that we have tailwindCSS, let these configurations become simpler! If your designer provides a common spacing scheme, such as multiples of 4px or 6px, now assuming that the designer’s design is 750px, we can write two function methods based on this to handle pxtoREM and pxtoVW tasks. If you are flexable, use PxtoREM. PxToVmin is used for viewport adaptation.

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: [],}Copy the code

Of course, rounded corner size, border width and so on can be configured so, is not more elegant than using plug-ins

Nested syntax

Some students may be interested in CSS preprocessor nested syntax, tailwindcss can be used? Arrangement! Tailwindcss there is a plugin called @tailwindCSS /nesting, based on some configuration in the official website, note that the documentation is to configure tailwindCSS /nesting for PostCSS, actually I need to configure @tailwindcss/nesting, Then you can provide the ability to nest based on CSS

Truncate after fixed number of lines

Sometimes we will write a stage after line X in order to write text and display… It takes several lines of style code, so we usually define one of these SCSS utility functions

@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;
}
Copy the code

Tailwindcss has a proprietary plugin @tailwindCSS /line-clamp for this particular case, just install it and import it in plugins in tailwind.config.js

Installing a plug-in

npm install -D @tailwindcss/line-clamp
Copy the code

configuration

// tailwind.config.js
module.exports = {
  // ...
  plugins: [
    require('@tailwindcss/line-clamp'),],}Copy the code

use

<div class="line-clamp-3">
  <! -... 3 lines after truncation -->  
<div>
Copy the code

More topics

Maybe you are maintaining a project that needs to support multiple themes, and there are multiple color schemes for different situations. Implementing multi-theme color schemes with CSS var in tailwindcss can be extremely simple:

Configure the theme in your global CSS file, assuming we have three different theme colors: SUCCESS, INFO, and Warning

/* global base css */
@tailwind base;
@tailwind components;
@tailwindutilities; // The default theme:root {
  --success: 5 193 174;
  --info: 51 163 238;
  --warning: 237 214 18; } / / theme1The color matching.theme-1 {
  --success: 36 195 102;
  --info: 54 143 255;
  --warning: 234 209 27; } / / theme2The color matching.theme-2 {
  --success: 57 209 121;
  --info: 0 186 255;
  --warning: 234 209 27;
}
Copy the code

Then go to our tailwind.config.js and change our color configuration

// Let our colors support transparency Settings
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')]},Copy the code

Finally, set your theme according to different circumstances. Set the corresponding class for the top element of the theme to be set. All the internal color styles will change according to the specific theme!

<! -- Default theme -->
<div>
  <! -... -->
</div>
<! -- Theme 1 -->
<div class="theme-1">
  <! -... -->
</div>
<! -- Theme 2 -->
<div class="theme-2">
  <! -... -->
</div>
Copy the code

Some best practices

  • If some element styles are particularly complex, causehtmlHow to optimize long messy code? You can go throughtailwindcssTo provide the@applyDirectives represent a series of styles through a semantically defined class
<div class="complex-node">xxxx<div>

// ...
<style>
.complex-node {
  @apply flex m-3text-success rounded .... ; }</style>
Copy the code
  • I have some styles that are universal, such as buttons and some styles of cards. How should I maintain them? You can go throughtailwindcssTo provide the@layerThe directive will compare generic styleslayertocomponentsLayer, as a component-level style, thus enabling global reuse
@layer components {
  .btn-blue {
    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4rounded; }}Copy the code
  • My project is maintained by multiple people. How do I ensure that the atomized style class names are in a reasonable order? For example, if you like to write width and height first and then position, but your colleague is the opposite, how to make a specification?tailwindcssProvided aprettierThe plug-inprettier-plugin-tailwindcss, you can standardize the formatting of classes with different member write styles by installing plug-ins and configuring them to be saved and updated
npm install -D prettier prettier-plugin-tailwindcss
Copy the code

Prettierrc. json type {} For your project, or if it’s a personal project, install esbenp.prettier-vscode Format On Paste and Format On Save are checked, and the order of your style classes is automatically sorted according to the CSS box Model from outside to inside:

marginborderpaddingcontent

conclusion

Just for the usual part of the author used to tailwindCSS ability for some talk, in fact, there are a lot of ability are not said, such as V3 to provide some for the print page style, hover, active, pseudo class and so on some Settings, in fact, is relatively simple, specific use of the time to see the official document can be. Tailwindcss has a lot of basic class names that need to be memorized. Practice makes perfect, all of which are once and for all things. Let me know if you have a good configuration or best practices in the comments section. Finally, useful please like, like please pay attention to, I am Senar (public number of the same name), thank you!

Content of the past

Basic productivity literacy for front-end development (updated from time to time)

Remember once introducing TypeScript and the composite Api and Vueuse into a tired Vue2 project to improve the big guy’s development experience

For frontend developers, it’s time to start using PNPM

This article will let you thoroughly use the object storage OSS front-end direct pass, do not understand to see again! (bushi)