CSS中linear-gradient 的用法

linear-gradientCSS 渐变背景 的一种写法,用于生成沿着直线方向的颜色过渡效果。它常和 backgroundbackground-image 属性一起使用。


基本语法

css 复制代码
background: linear-gradient(direction, color-stop1, color-stop2, ...);
  • direction(方向) :可以是角度(如 45deg)、关键字(如 to right, to bottom 等)。
  • color-stop(颜色停靠点):颜色值,可以指定位置(百分比或长度),决定渐变分布。

方向写法

  1. 默认(从上到下)

    css 复制代码
    background: linear-gradient(red, blue);

    → 从上方的红色过渡到底部的蓝色。

  2. 使用关键字

    css 复制代码
    background: linear-gradient(to right, red, blue);

    → 从左到右渐变。

    css 复制代码
    background: linear-gradient(to bottom right, red, blue);

    → 从左上到右下渐变。

  3. 使用角度

    css 复制代码
    background: linear-gradient(45deg, red, blue);

    → 沿 45° 方向渐变。


颜色停靠点

你可以通过百分比或长度控制颜色分布:

css 复制代码
background: linear-gradient(to right, red 0%, yellow 50%, green 100%);
  • 0%:最左侧是红色
  • 50%:中间是黄色
  • 100%:最右侧是绿色

重复渐变

使用 repeating-linear-gradient 可以创建重复的渐变:

css 复制代码
background: repeating-linear-gradient(45deg, red 0, red 10px, blue 10px, blue 20px);

→ 形成条纹效果。


常见应用

  1. 按钮背景

    css 复制代码
    button {
      background: linear-gradient(to right, #ff7e5f, #feb47b);
      border: none;
      padding: 10px 20px;
      color: white;
      border-radius: 8px;
    }
  2. 渐变分隔线

    css 复制代码
    hr {
      border: 0;
      height: 3px;
      background: linear-gradient(to right, transparent, #333, transparent);
    }

相关推荐
excel9 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel10 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼12 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping12 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙13 小时前
[译] Composition in CSS
前端·css
白水清风13 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix13 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780013 小时前
new、原型和原型链浅析
前端·javascript
阿星做前端13 小时前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧13 小时前
Promise 的使用
前端·javascript