CSS

38 阅读3分钟

1、saas、less、postcss的使用举例

一、Sass(Syntactically Awesome Style Sheets)

定位:功能最全面的 CSS 预处理器,支持变量、嵌套、混入(Mixin)、继承等,语法有 .scss(类 CSS 语法)和 .sass(缩进语法)两种,推荐用 .scss

核心特性及示例

  1. **变量(Variables)**复用颜色、尺寸等,方便全局维护。

    scss

    // 定义变量
    $primary-color: #4285f4;
    $font-size: 16px;
    
    .button {
      color: $primary-color;
      font-size: $font-size;
    }
    

    编译后:

    css

    .button {
      color: #4285f4;
      font-size: 16px;
    }
    
  2. **嵌套(Nesting)**模拟 HTML 层级结构,减少重复选择器。

    scss

    .card {
      padding: 20px;
      border: 1px solid #eee;
    
      // 嵌套子元素
      .title {
        font-size: 20px;
        color: #333;
      }
    
      // 嵌套伪类
      &:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
    }
    

    编译后:

    css

    .card {
      padding: 20px;
      border: 1px solid #eee;
    }
    .card .title {
      font-size: 20px;
      color: #333;
    }
    .card:hover {
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
  3. **混入(Mixin)**复用代码块(支持参数),类似函数。

    scss

    // 定义带参数的Mixin
    @mixin flex-center($direction: row) {
      display: flex;
      flex-direction: $direction;
      justify-content: center;
      align-items: center;
    }
    
    .header {
      @include flex-center(); // 调用Mixin,使用默认参数
      height: 60px;
    }
    
    .sidebar {
      @include flex-center(column); // 传入参数
      width: 200px;
    }
    

    编译后:

    css

    .header {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      height: 60px;
    }
    .sidebar {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 200px;
    }
    

二、Less(Leaner Style Sheets)

定位:轻量的 CSS 预处理器,语法与 CSS 更接近,核心功能(变量、嵌套、Mixin)与 Sass 类似,学习成本较低。

核心特性及示例

  1. 变量用 @ 定义变量(与 Sass 的 $ 不同)。

    less

    @primary-color: #4285f4;
    @font-size: 16px;
    
    .button {
      color: @primary-color;
      font-size: @font-size;
    }
    
  2. 嵌套语法与 Sass 一致,支持 & 引用父选择器。

    less

    .card {
      padding: 20px;
      .title {
        font-size: 20px;
      }
      &:active {
        opacity: 0.8;
      }
    }
    
  3. **Mixin(无需 @mixin 关键字)**直接用类选择器定义,通过 () 调用。

    less

    // 定义Mixin
    .flex-center(@direction: row) {
      display: flex;
      flex-direction: @direction;
      justify-content: center;
    }
    
    .footer {
      .flex-center(column); // 调用Mixin
      height: 80px;
    }
    

三、PostCSS

定位:CSS 后处理器(基于插件的工具),本身不提供语法扩展,而是通过插件实现各种功能(如自动前缀、CSS 变量兼容、代码压缩等)。

核心用法

  1. 安装 PostCSS 及所需插件(如 autoprefixer 自动加浏览器前缀):

    bash

    npm install postcss autoprefixer --save-dev
    
  2. 配置 postcss.config.js

    javascript

    运行

    module.exports = {
      plugins: [
        require('autoprefixer')({
          overrideBrowserslist: ['last 2 versions', 'iOS >= 10'] // 兼容目标浏览器
        })
      ]
    };
    
  3. 编写原始 CSS(无需手动加前缀):

    css

    .box {
      display: flex;
      transition: all 0.3s;
    }
    
  4. 经 PostCSS 处理后(自动添加前缀):

    css

    .box {
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-transition: all 0.3s;
      transition: all 0.3s;
    }
    

常用 PostCSS 插件

  • autoprefixer:自动添加浏览器前缀(替代手动写 -webkit--ms- 等)。
  • postcss-preset-env:将现代 CSS 特性(如 CSS 变量、::slotted)转换为兼容旧浏览器的语法。
  • cssnano:压缩 CSS 代码(移除空格、合并重复规则等)。
  • postcss-import:支持 CSS 中的 @import 语法(合并多个 CSS 文件)。

总结:三者的区别与选择

工具类型核心能力适用场景
Sass预处理器变量、嵌套、Mixin、继承等语法扩展大型项目,需要复杂样式逻辑复用
Less预处理器轻量语法扩展,接近原生 CSS中小型项目,追求简单易用
PostCSS后处理器基于插件实现自动化(前缀、压缩等)任何项目,用于增强 CSS 工程化能力(常与 Sass/Less 配合使用)

实际开发中:通常将 Sass/Less 作为预处理器编写样式,再用 PostCSS(如 autoprefixer)进行后处理,结合两者优势。

CSS Modules Sass/SCSS CSS-in-JS (styled-components, emotion 等) Tailwind CSS 分别介绍这几个的使用

1. CSS Modules

CSS Modules 是一种将 CSS 类名局部化的方案,避免全局样式冲突,通常与构建工具(如 Webpack、Vite)结合使用。

核心特性:
  • 类名被编译为唯一哈希值(如 header__title_123abc),作用域仅限当前组件。
  • 支持组合类名、全局样式声明。
使用步骤:
  1. 命名规范:样式文件命名为 [name].module.css(或 .scss)。

  2. 在组件中导入

    css

    /* Button.module.css */
    .button {
      padding: 8px 16px;
      background: blue;
      color: white;
    }
    .disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    

    jsx

    // Button.jsx
    import styles from './Button.module.css';
    
    export default function Button({ disabled }) {
      return (
        <button className={`${styles.button} ${disabled ? styles.disabled : ''}`}>
          Click me
        </button>
      );
    }
    
  3. 全局样式:使用 :global() 声明全局类名:

    css

    :global(.global-class) {
      margin: 0;
    }
    
适用场景:
  • 中大型项目,需严格隔离组件样式。
  • 与 React、Vue 等框架结合使用。

2. Sass/SCSS

Sass 是 CSS 预处理器,扩展了 CSS 语法,支持变量、嵌套、混合(Mixin)、继承等特性,.scss 是其主流语法(兼容 CSS)。

核心特性:
  • 变量$primary-color: #4285f4;
  • 嵌套:避免重复选择器。
  • Mixin:复用样式片段(支持传参)。
  • 继承:通过 @extend 复用样式。
  • 函数与运算:颜色计算、数值运算等。
使用步骤:
  1. 安装依赖

    bash

    运行

    npm install sass --save-dev  # 或 dart-sass
    
  2. 编写 SCSS 文件

    scss

    // variables.scss
    $primary: #4285f4;
    $border-radius: 4px;
    
    // Button.scss
    @import './variables';
    
    .button {
      padding: 8px 16px;
      background: $primary;
      border-radius: $border-radius;
    
      &:hover {
        background: darken($primary, 10%);
      }
    
      &.disabled {
        opacity: 0.5;
        @extend .cursor-not-allowed;
      }
    }
    
    .cursor-not-allowed {
      cursor: not-allowed;
    }
    
  3. 在组件中导入

    jsx

    import './Button.scss';
    
    function Button() {
      return <button className="button disabled">Click</button>;
    }
    
适用场景:
  • 需要复杂样式逻辑、复用性高的项目。
  • 兼容 CSS 生态,可逐步迁移。

3. CSS-in-JS(styled-components/emotion)

CSS-in-JS 将 CSS 样式写在 JavaScript 中,样式与组件紧密耦合,支持动态样式、作用域隔离。

主流库:
  • styled-components:基于模板字符串,组件化样式。
  • emotion:支持模板字符串和 JSX 语法,性能更优。
使用示例(styled-components):
  1. 安装

    bash

    运行

    npm install styled-components
    
  2. 编写组件

    jsx

    import styled, { css } from 'styled-components';
    
    // 基础样式组件
    const Button = styled.button`
      padding: 8px 16px;
      background: ${props => props.primary ? '#4285f4' : 'white'};
      color: ${props => props.primary ? 'white' : '#333'};
      border: 1px solid #ddd;
      border-radius: 4px;
    
      &:hover {
        opacity: 0.9;
      }
    
      // 动态样式
      ${props => props.disabled && css`
        opacity: 0.5;
        cursor: not-allowed;
      `}
    `;
    
    // 使用
    function App() {
      return (
        <div>
          <Button primary>Primary Button</Button>
          <Button disabled>Disabled Button</Button>
        </div>
      );
    }
    
使用示例(emotion):

jsx

import { css, styled } from '@emotion/react';

const baseStyle = css`
  padding: 8px 16px;
  border-radius: 4px;
`;

const PrimaryButton = styled.button`
  ${baseStyle};
  background: #4285f4;
  color: white;
`;
核心特性:
  • 样式随组件动态变化(基于 props)。
  • 自动生成唯一类名,无样式冲突。
  • 支持主题(ThemeProvider)、全局样式。
适用场景:
  • 组件库开发、需要高度动态样式的场景。
  • React 项目(主流 CSS-in-JS 库多针对 React)。

4. Tailwind CSS

Tailwind CSS 是原子化 CSS 框架,提供预定义的原子类(如 flexp-4text-red-500),无需编写传统 CSS。

核心特性:
  • 原子类优先,直接在 HTML/JSX 中组合样式。
  • 高度可定制(通过 tailwind.config.js 配置主题、颜色、间距等)。
  • 支持响应式设计(sm:md: 前缀)、伪类(hover:focus:)。
使用步骤:
  1. 安装配置

    bash

    运行

    npm install -D tailwindcss postcss autoprefixer
    npx tailwindcss init -p
    
  2. 配置 tailwind.config.js

    js

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: ["./src/**/*.{js,jsx,ts,tsx}"], // 指定文件路径
      theme: {
        extend: {
          colors: {
            primary: '#4285f4',
          },
        },
      },
      plugins: [],
    };
    
  3. 导入基础样式

    css

    /* index.css */
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
  4. 使用原子类

    jsx

    function Button({ primary, disabled }) {
      return (
        <button
          className={`px-4 py-2 rounded ${
            primary ? 'bg-primary text-white' : 'bg-white text-gray-800 border border-gray-300'
          } ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:opacity-90'}`}
          disabled={disabled}
        >
          Click me
        </button>
      );
    }
    
进阶用法:
  • 自定义组件类:在 @layer components 中封装复用样式:

    css

    @layer components {
      .btn-primary {
        @apply px-4 py-2 bg-primary text-white rounded hover:opacity-90;
      }
    }
    

    使用:<button className="btn-primary disabled:opacity-50">Button</button>

适用场景:
  • 快速开发原型、中小型项目、追求高效迭代的场景。
  • 需要统一设计系统且减少 CSS 编写的项目。

方案对比

方案优点缺点适用场景
CSS Modules局部作用域、简单易用动态样式需拼接类名中大型组件化项目
Sass/SCSS语法扩展、复用性强需编译,全局样式易冲突复杂样式逻辑、传统 CSS 迁移
CSS-in-JS动态样式、组件耦合运行时开销、调试稍复杂React 组件库、动态样式场景
Tailwind CSS开发高效、高度定制HTML 类名冗长、学习成本快速开发、设计系统统一项目

根据项目需求选择即可,也可混合使用(如 Tailwind + CSS Modules)。

编辑分享

如何在React项目中使用CSS Modules?