React第三十章(css原子化)

原子化 css

什么是原子化 css

原子化 CSS 是一种现代 CSS 开发方法,它将 CSS 样式拆分成最小的、单一功能的类。比如一个类只负责设置颜色,另一个类只负责设置边距。这种方式让样式更容易维护和复用,能提高开发效率,减少代码冗余。通过组合这些小型样式类,我们可以构建出复杂的界面组件。

原子化 css 基本概念

原子化 css 是一种css的编程范式,它将css的样式拆分成最小的单元,每个单元都是一个独立的css类,通过这些独立的css类来构建整个页面的样式,简单举个例子:

其核心思想就是无需重复定义样式,只需定义一次,然后通过组合这些小型样式类,来构建出复杂的界面组件。

html 复制代码
<style>
  .color-red { color: red }
  .text-center { text-align: center }
  .p-10 { padding: 10px }
</style>
<section class="bg-red text-center p-10">
    原子化 css
</section>

那么有谁在用呢?

例如比较知名的网站有: x Github 等,他们都是使用原子化 css 来构建他们的网站。

TailWind Css

TailWind Css 官网

TailWind 是原子化 css 的一种实现方式,它内置了许多细粒度的 class 类,这些细粒度的 class 类可以组合使用,来构建出复杂的界面组件。

如何使用 TailWind Css 4.0.1 最新版

  • vite 项目
sh 复制代码
npm install tailwindcss @tailwindcss/vite
  1. vite.config.ts

引入 tailwindcss 插件,然后配置 tailwindcss 插件

ts 复制代码
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
  plugins: [react(), tailwindcss()],
})
  1. src/tailwind.css (新建一个文件) 引入 tailwindcss 的样式
css 复制代码
@import "tailwindcss";
  1. src/main.tsx

引入 tailwindcss 的样式

tsx 复制代码
import './tailwind.css'
  1. src/App.tsx 试用 tailwindcss 的样式
tsx 复制代码
<section class="bg-red text-center p-10">
    原子化 css
</section>
  1. 打开Vscode或者Cursor,安装 TailWind Css 插件,这样编写代码的时候,会自动提示 tailwindcss 的样式

案例

简单使用 tailwindcss 来构建一个 欢迎页

tsx 复制代码
import React, { } from 'react';
const App: React.FC = () => {
  return (
    <>
      <div className="bg-gradient-to-r from-pink-600 to-purple-600 h-screen w-screen flex justify-center items-center">
          <div className='text-white text-4xl font-bold hover:text-gray-300'>
             大家好我是小满zs,欢迎来到我的博客
          </div>
      </div>
    </>
  );
}

export default App;

进阶用法@apply

我们可以看到上述代码中,类名用了很多都是堆在一起的,这样看起来很不美观,我们可以使用 tailwindcss@apply 来解决这个问题。

  • src/tailwind.css
css 复制代码
@import "tailwindcss";

.blob-bg {
    @apply bg-gradient-to-r from-pink-600 to-purple-600 h-screen w-screen flex justify-center items-center;
}

.blob-text {
    @apply text-white text-4xl font-bold hover:text-gray-300;
}
  • src/App.tsx

效果是一样的,但是看起来更美观了

tsx 复制代码
<div className="blob-bg">
    <div className="blob-text">
        大家好我是小满zs,欢迎来到我的博客
    </div>
</div>

更多用法请参考 tailwindcss 自定义样式

相关推荐
IT_陈寒1 分钟前
SpringBoot 项目启动慢?5 个提速技巧让你的应用快如闪电 ⚡️
前端·人工智能·后端
IT_陈寒4 分钟前
SpringBoot自动配置的坑,我把头发都快薅没了
前端·人工智能·后端
xkxnq8 分钟前
第六阶段:Vue生态高级整合与优化(第96天) Vue i18n优化:语言包按需加载+缓存当前语言+避免页面刷新失效
前端·vue.js·缓存
Dxy123931021612 分钟前
Ajax如何发送列表数据
前端·ajax·okhttp
C澒14 分钟前
微前端容器标准化 —— 公共能力篇:通用跨框架通信能力
前端·架构
榴莲omega16 分钟前
第8天:前端面试经典五问
前端·面试·职场和发展·js八股
资讯第一线22 分钟前
RAD Studio 13.1 [DELPHI 13.1] [官方原版IOS] 下载
前端
橘子编程24 分钟前
CSS 全栈指南:从基础到 2025 新特性
前端·css·chrome·tensorflow·less·css3·html5
不会写DN32 分钟前
从依赖到自主:手写一个 ICO 文件转换器
前端·javascript·typescript·node.js