directory

  • Atomic/functional classes are preferred

  • Let’s start with Semantic CSS

  • The Atomic/Utility – First CSS

  • Rich functional classes

  • Production optimization

  • Configuration Purge

  • Just-in-time JIT

  • Development practices

  • Use the Playground

  • Used in React

  • Used in VS Code

Atomic/functional classes are preferred

Let’s start with Semantic CSS

To style a business card, we usually write: add a semantically assigned class name to an HTML or JSX structure, and then write the corresponding class style in CSS.

This is the most common and conventional way of writing, and is called the Semantic CSS specification. Under this specification, we pursue separation of concerns, let structure and style do their respective jobs, and make structure more semantic. However, there are also many problems in many scenarios, such as:

  • Each tag has its own class, but even adding a small style to a tag requires us to come up with a class name that is semantic, conforms to the code specification, and is distinct from other tag class names that have similar functions.

  • There are often many style rules in each class. Only when the semantic and style of the structure are completely the same, can the real reuse be achieved. If there is a little difference, it is difficult to achieve style reuse.

  • We can remove the style by deleting the class name in HTML or JSX, but we can’t easily remove the CSS style from that class because we can’t guarantee that the class has been used elsewhere, and we have the same problem when changing the style in a class.

  • If we migrate HTML or JSX structures, we also migrate the corresponding CSS, and even then, the migrated styles may become confusing depending on the context;

  • .

Bootstrap can be thought of as a componentized framework based on Semantic CSS. Take the button component as an example, it predefined a variety of button styles, encapsulate different styles into different class components, and each style has its own semantic purpose, such as success is green, danger danger represents red…… In use, we don’t have to worry about the tedious CSS and just refer to the corresponding class name. But such componentized CSS, if you want to implement custom styles, may require more effort to do style coverage.

The Atomic/Utility – First CSS

Atomic/Utility-First CSS in contrast to Semantic CSS, utility-first CSS does not put component styles in a class as Semantic CSS does, It gives us a toolbox of different functional classes that we can mix and apply to HTML elements. In the case of Atomic CSS, atoms form the smallest unit of matter in the physical world, whereas in the CSS world there is only one CSS rule in a class.


<style>

/* Atomic/Utility-First CSS */

.bg-black {

background-color: black;

}

.text-white {

color: white;

}

.rounded-8 {

border-radius: 8px;

}

/* Utility-first CSS, non-atomic CSS */

.py-8 {

padding-top: 8px;

padding-bottom: 8px;

}

.px-5 {

padding-left: 20px;

padding-right: 20px;

}

</style>




<button class="bg-black text-white rounded-8 py-2 px-5">button</button>

Copy the code

Tailwind CSS is similar to Bootstrap in that it uses class names to refer to styles. But the biggest difference is at the heart of Tailwind CSS, which is a CSS framework based on Atomic/Utility-First CSS. Also for business card style development, Tailwind CSS does this:

The Tailwind CSS framework based on the Atomic/ Utility-FIRST CSS specification has the following advantages:

  • Don’t spend time thinking of nasty class names;

  • The simpler the function of the class, the higher the reuse rate;

  • Tightly coupled structure and style, no switching between HTML and CSS, more focused on HTML;

  • Modifying a style does not affect other structural styles;

  • Ensure global style unity, there is no global style pollution problem;

  • When the structure migrates, the corresponding style remains;

  • Rich functionality classes that cover most development scenarios;

  • .

But there are also visible problems:

  • There are too many classes to refer to. But in Tailwind you can also extract component styles with @apply;

  • You can’t know the function of an element by semantizing the class name. However, in today’s componentized development, it is more important to understand the function of the component itself than the function of a tag element in the component.

  • Tailwind has a lot of features and is not too small. But you can configure Purge to remove useless stuff;

  • .

Rich functional classes

  • Size: in Tailwind, 1 corresponds to 0.25rem, and py-2 represents the padding on the Y-axis, i.e., padding-top and padding-bottom are 0.5rem;

  • Size: use sm/base/ LG table to mark the size and line height. For example, text-sm indicates that the size is 14px and the line height is 20px.

  • Color: Indicates the depth of a color by a number from 50 to 900, such as text-gray-500, corresponding to #6B7280 in the color card;

  • Responsive design

Tailwind sets the default 5 breakpoints based on common screen resolutions: SM (640px), MD (768px), LG (1024px), XL (1280px), and 2XL (1536px).


<div class="h-12 border sm:w-1/2 md:w-48"></div>

Copy the code

Sm: W-1/2, MD: W-48 equivalent to:


@media (min-width: 640px) {

.sm\:w-1/ /2 {

width: 50%; }}@media (min-width: 768px) {

.md\:w-48 {

width: 12rem/ *192px */;

}

}

Copy the code
  • State of suspension

Tailwind uses function classes to style elements in various states, including Hover, Active, Focus, Disabled, first-child, last-Child, and so on.


/* hover */

<button class="bg-red-500 hover:bg-red-700 ...">

Hover me

</button>




/* group-hover */

<div class="hover:bg-gray-800 group">

<h1 class="group-hover:text-white">title</h1>

<span class="text-gray-500 group-hover:text-white">i am content</span>

</div>/* is used in combination with the responsive prefix */<button class="... hover:bg-green-500 sm:hover:bg-blue-500">

Hover me

</button>

Copy the code
  • Dark mode

Tailwind supports dark mode, just add the Dark variant. This parameter is required when you use this mode. It is disabled by default to reduce the file size.


<div class="bg-white dark:bg-gray-800">

<p class="text-gray-900 dark:text-white">Dark mode is here!</p>

</div>

Copy the code
  • Custom Configuration

Tailwind can solve most development scenarios, and it can also override existing configurations or add custom configurations via Tailwind.


// tailwind.config.js

module.exports = {

purge: [].darkMode: false.// It is disabled by default

theme: { / / theme

colors: {},

fontFamily: {},

extend: {},},variants: { / / variant

extend: {},},plugins: []./ / the plugin

perset: []./ / the default

prefix: ' './ / prefix

important: true./ / enabled! important. }Copy the code
  • More Tailwind CSS features such as flexible layouts, backgrounds, borders, transitions, and animations are explained in detail in the Tailwind CSS documentation.

Production optimization

Tailwind’s rich feature classes give it a large base of size compared to other frameworks, but because Tailwind’s rich feature classes have a single function, it has a much higher reuse rate, with fewer new CSS and more pages, resulting in a larger gain in packaging volume. In addition, Tailwind has made production optimizations such as purge and its just-in-Time mode, released In version 2.1.

Configuration Purge

Tailwind has thousands of feature classes, but not all of them are required, and we can optimize the final build size by setting the Purge option in the configuration file and tree-shake to remove unused styles.

  • Enabled: Whether to enable it. The value can be set to false during development.

  • Content: indicates the file path to be checked.

  • Layers: Cleans up all styles in a particular layer


module.exports = {

purge: {

enabled: true.content: ['./src/**/*.{js,jsx,ts,tsx}'.'./public/index.html'].layers: ['components'.'utilities'],... },... }Copy the code

At the bottom of this functionality is the PurgeCSS library, which cleans like this:

  1. Scan we provide content files, for a specific file type, according to the extractor to extract the various attributes used;

  2. Parsing the CSS files we rely on, identifying all existing selectors, generating AST abstract syntax trees;

  3. The extracted information is matched with the AST abstract syntax tree, and the unused CSS rules are deleted from the syntax tree.

  4. Finally, in the case of NODE_ENV being production, the build generates a stylesheet that leaves only the styles used.

In Tailwind, we don’t have to set up the extractor, Tailwind has done everything for us, we just need to configure the file path that needs to be cleaned. In addition, when PurgeCSS scans a file, it looks for any string that matches the regular expression, so we need to write the full class name when dynamically determining the class name, rather than having the class name be dynamically concatenated. This ensures that PurgeCSS can find used classes and avoid accidentally deleting important styles.


` / [^ < > "' `\s]*[^<>"'`\s:]/g`

Copy the code

Just-in-time JIT

While PurgeCSS helps us eliminate unused classes in production, in development, the build tool still generates all classes. As a result, Tailwind generated larger and larger CSS packages, application builds became slower and slower, and Dev Tools was slow due to the amount of CSS to ingest, resulting in extremely high time and a poor development experience. Tailwind2.1 version of the JIT mode for us to solve this problem.

Differences between JIT and AOT:

  • JIT(Just In Time) : runtime when the application is compiled In the browser;

  • AOT(Ahead of Time) : The application is compiled on the server during construction.

Instead of creating everything ahead of time during the initial build, the JIT compiler generates templates on demand, monitors our HTML files, and only gets the CSS classes we really need. CSS is small, takes less time to build, and Dev Tools is more responsive. And previously, many Tailwind variants were disabled by default because they resulted in megabytes of CSS generation, but because the JIT generated styles “on demand,” they were enabled by default, meaning that all of these variants could be used directly with zero configuration.


// tailwind.config.js

module.exports = {

+ mode: 'jit'.purge: [

// ...].theme: {

// ...

}

// ...

}

Copy the code

At the same time, JIT “bundles” some more flexible writing:


<! -- Support any value -->

<button class="bg-[#1da1f1]">button</button>




<! -- Built-in important modifier -->

<p class="font-bold ! font-medium">

This will be medium even though bold comes later in the CSS.

</p>




<! Stackable variants -->

<button class="md:dark:disabled:focus:hover:bg-gray-400">

<! -- Short for Color/Opacity -->

<div class="bg-red-500/25">

and so on...

Copy the code

Development practices

Use the Playground

Before using Tailwind for development, you can use Tailwind Play, the online operating environment provided on Tailwind’s website. Here, you can compile your code in real time, configure CSS and Config files, give Tailwind syntax hints, hover over the class name to display the CSS source code, and share links to your work with others when you’re done.

Used in React

In the React project, install Tailwind, PostCSS, and Autoprefixer,

  • Tailwimd CSS is essentially a plugin for PostCSS (react itself installs an older version of PostCSS, so install the corresponding older version here).

  • Add the browser engine prefix automatically through Autoprefixer.


npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

Copy the code

Configuration Craco

CRA scaffolding encapsulates the WebPack configuration into the React-Scripts package, which is not visible by default. When the scaffold configuration does not meet requirements, the NPM run eject command exposes the configuration for our own management. But once eject is done, there is no way to restore or upgrade React-Scripts. The Craco tool allows you to customize webPack configurations and centrally manage all configurations without implementing Eject.

  1. Install the Craco tool in the React project

npm install @craco/craco

Copy the code
  1. Rewrite the scripts section in the package.json file

"scripts": {

"start": "craco start"."build": "craco build"."test": "craco test"."eject": "react-scripts eject"

},

Copy the code
  1. Manually create a craco.config.js file in the root directory, and add tailwind and autoprefix as PostCSS plug-ins

module.exports = {

style: {

postcss: {

plugins: [

require('tailwindcss'),

require('autoprefixer'),],},},}Copy the code

Introducing the Tailwind CSS

Run the tailwind command to initialize tailwind. After the initialization, the tailwind. Config. js file is generated in the root directory to enable the purge and other customized configurations.

npx tailwind init
Copy the code

In the SRC /index.css file, clean out the old styles and introduce tailwind with the @tailwind command

  • ** Base: ** the base style of tailwind, i.e. resetting the browser style;

  • ** Components: component classes defined by tailwind;

  • ** Utilities: The utility class for tailwind, which is the core of tailwind.


@tailwind base;

@tailwind components;

@tailwind utilities;

Copy the code

Alternatively, import tailwindCSS/tailwind.css directly into the js file


import "tailwindcss/tailwind.css"

Copy the code

Used in VS Code

In VS Code, install Tailwind CSS IntelliSense to have intelligent code hints: autocomplete, syntax check, hover preview, syntax highlighting;

In addition, we can also help reduce the burden of memory according to the checklist.

Refer to the link

  • Tailwind CSS official documentation

  • Atomic CSS-in-JS

  • CSS Utility Classes and “Separation of Concerns”

  • Tailwind generated a whopping 3.7MB CSS file! This still works?

  • Drastically reducing your stylesheet size with Tailwind and PurgeCSS

  • Why Tailwind’s just-in-time mode is a game-changer and how to use it right Now Patterns change the rules of the game and how to use them immediately)