CSS 线性渐变

CSS 线性渐变

线性渐变(linear-gradient)是CSS中创建颜色平滑过渡的强大工具。

基本语法

background-image: linear-gradient(渐变方向, 颜色1 变化区间, 颜色2 变化区间, ... 颜色n变化区间);

渐变方向

  1. 使用角度:0deg(上到下)、90deg(左到右)、180deg(下到上)

    background-image: linear-gradient(45deg, red, blue);
    
  2. 使用关键词

    1. to top(从下到上)
    2. to right(从左到右)
    3. to bottom(默认,从上到下)
    4. to left(从右到左)
    5. 也可以组合:to top right(从左下到右上)

色标(Color Stops)

  1. 基本色标

    background-image: linear-gradient(red, yellow, green);
    
  2. 指定位置

    1. 百分比:red 0%, yellow 50%, green 100%
    2. 具体长度:red 0px, yellow 100px, green 200px
  3. 色标间硬过渡(不使用渐变):

    background-image: linear-gradient(red 50%, blue 50%);
    

重复线性渐变

background-image: repeating-linear-gradient(angle, color-stop1, color-stop2, ...);
background-image: repeating-linear-gradient(45deg, red, red 10px, blue 10px, blue 20px);

实际应用示例

渐变文字

background-image: repeating-linear-gradient(45deg, red, red 10px, blue 10px, blue 20px);
-webkit-background-clip: text;
color: transparent;

高级技巧

  1. 多重渐变

    background: 
      linear-gradient(45deg, rgba(0,0,255,0.2) 0%, rgba(0,0,255,0) 50%),
      linear-gradient(-45deg, rgba(255,0,0,0.2) 0%, rgba(255,0,0,0) 50%);
    
  2. 创建对角线条纹

    background: repeating-linear-gradient(
      45deg,
      #606dbc,
      #606dbc 10px,
      #465298 10px,
      #465298 20px
    );
    

注意事项

  1. 渐变被视为背景图像,不是背景颜色

  2. 可以与其他背景属性结合使用

    1. 背景裁剪(渐变文字)

       background: linear-gradient(to right, red, yellow);
       background-clip: text; /* 只对文字内容应用背景 */
       color: transparent;
      
  3. 渐变可以应用于任何接受图像的属性

    1. border-image

      border: 10px solid;
      border-image: linear-gradient(45deg, purple, orange) 1;
      
posted @ 2025-07-29 22:32  HuangBingQuan  阅读(40)  评论(0)    收藏  举报