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);
    }

相关推荐
N***73851 天前
Vue网络编程详解
前端·javascript·vue.js
e***71671 天前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
程序猿小蒜1 天前
基于springboot的的学生干部管理系统开发与设计
java·前端·spring boot·后端·spring
银空飞羽1 天前
让Trae CN SOLO自主发挥,看看能做出一个什么样的项目
前端·人工智能·trae
西游音月1 天前
(4)pytest+Selenium自动化测试-元素定位之CSS Selector定位
css·selenium·pytest
Eshine、1 天前
解决前端项目中,浏览器无法正常加载带.gz名称的文件
前端·vue3·.gz·.gz名称的js文件无法被加载
用户47949283569151 天前
别再当 AI 的"人肉定位器"了:一个工具让 React 组件秒定位
前端·aigc·ai编程
WYiQIU1 天前
面了一次字节前端岗,我才知道何为“造火箭”的极致!
前端·javascript·vue.js·react.js·面试
qq_316837751 天前
uniapp 观察列表每个元素的曝光时间
前端·javascript·uni-app
小夏同学呀1 天前
在 Vue 2 中实现 “点击下载条码 → 打开新窗口预览 → 自动唤起浏览器打印” 的功能
前端·javascript·vue.js