添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Back

Dec 28, 2022

Dec 28, 2022

Tailwind @Apply: Replacing Complex Classes with Tailwind CSS

Let's explore the Tailwind CSS utility @apply — a directive that allows developers to combine a collection of utilities into a reusable component class.

decorative cover image showing CSS and JavaScript textbooks
decorative cover image showing CSS and JavaScript textbooks
decorative cover image showing CSS and JavaScript textbooks

What is Tailwind CSS?

Tailwind CSS is an open-source utility-based CSS framework that provides a set of customizable utilities for constructing web designs and layouts.

The key difference between Tailwind CSS framework and other CSS frameworks like Bootstrap and Material UI is that it does not contain a collection of preset classes for components such as buttons and tables. Instead, it includes extensive utility classes for grids, margins, forms, placement, and so forth.

Tailwind CSS automatically removes any extraneous CSS, resulting in the shortest CSS bundle possible when building for production.

How to Install Tailwind CSS into Your Project

The Tailwind CLI tool is the quickest and easiest way to embed Tailwind CSS into your project from scratch. Check that you have Node.js installed before you begin.

Step 1 : Install Tailwind CSS into your project with the following command:

npm install -D tailwindcss

Save this code

Step 2: Then, create a tailwind.config.js file with this command:

npx tailwindcss init

Save this code

Step 3 : In your tailwind.config.js file, add the paths to all of your template files like this:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  plugins: [],
}

Save this code

Step 4 : Add the @tailwind directives to your main CSS file to represent each of Tailwind's layers.

@tailwind base;
@tailwind components;
@tailwind utilities;

Save this code

Step 5 : Add your compiled CSS file to the of your markup file and begin styling your content with Tailwind's utility classes.

Save this code

To ensure you are setting up you Tailwind properly, you can watch this video to Install tailwind css from scratch using the CLI

Getting Started with Tailwind CSS @apply

Tailwind CSS’s @apply directive is a relatively new feature in the Tailwind CSS ecosystem that allows developers to “apply” existing utility classes in line with their custom CSS. It is convenient when you need to write custom CSS (for example, to override styles in a third-party library) but still want to work with your design tokens and use the same syntax as you would in HTML.

@tailwind base;
@tailwind components;
@tailwind utilities;
.class {
 background-color: blue;
 border-radius: 50%;
/* re-using the styling for the first class here */
.class-2 {
 @apply class;
/* applying Tailwind CSS utility classes */
.another__class {
 @apply border border=gray-300 rounded;