CSS线性渐变需用background属性而非background-color,推荐方位关键词如to right,确保html/body高度100%且无margin,并注意background-color会覆盖渐变。

用 CSS background 设置线性渐变背景
直接在 index.html 的 <style></style> 标签或外部 CSS 文件中写 background: linear-gradient(...) 就能生效,不需要 JS 或额外库。
常见错误是只写了 background-color —— 这个属性不支持渐变,必须用 background(或 background-image)。
-
background可以同时覆盖颜色、图片、渐变,优先级高于background-color - 方向参数如
to right比90deg更易读,推荐用方位关键词 - 至少两个色值,比如
linear-gradient(to bottom, #fff, #000) - 如果页面内容少、高度不够,渐变可能“显示不全”,需确保
html和body高度撑满:html, body { height: 100%; margin: 0; }
渐变失效?检查这三处常见漏点
渐变写对了但没看到效果,大概率卡在这几个地方:
-
body默认有margin,会留白遮挡渐变 —— 加body { margin: 0; } - 只给
div或某个容器设了渐变,但没给html/body设height: 100%,导致容器高度为 0 - 用了
background-color覆盖了background,浏览器按层叠规则丢弃了渐变
兼容老浏览器时要不要加 -webkit- 前缀?
现在主流浏览器(Chrome 26+、Firefox 16+、Safari 6.1+、Edge 12+)都原生支持 linear-gradient,无需前缀。
生成可在 deepbi 沙箱 iframe 内运行或作为独立文件运行的交互式 HTML 页面,使用 `window.deepbi` JS SDK 实现数据查询、空间管理、文件浏览及用户操作。当用户提出以下需求时启用该能力: - 创建 KPI 仪表盘、数据表格、文件浏览器、成员列表、管理页面; - 明确要求“转成 dhtml”、“转译成 HTML”、“把 XX 页面转成……”、“控制台页面”、“管理后台”、“DeepBI 页面迁移”; - 提及位于 `apps/console/src/featur
立即学习“前端免费学习笔记(深入)”;
如果你明确要支持 iOS Safari -webkit-linear-gradient。但这类设备占比极低,多数项目可忽略。
- 现代写法:
background: linear-gradient(135deg, #ff9a9e, #fad0c4) - 兼容写法(不推荐堆砌):
background: -webkit-linear-gradient(135deg, #ff9a9e, #fad0c4);<br>background: linear-gradient(135deg, #ff9a9e, #fad0c4);
想让渐变随滚动动?别用 fixed 乱试
默认渐变是随元素滚动的。如果希望它固定在视口(类似“背景贴住屏幕”),得加 background-attachment: fixed。
但要注意:在部分 iOS Safari 和旧版 Android 上,fixed 会导致渲染异常或性能掉帧;另外,如果父容器用了 transform 或 will-change,也可能让 fixed 失效。
- 安全做法:只对
body或全屏section使用background-attachment: fixed - 替代思路:用伪元素
::before+position: fixed控制更精准 - 调试时临时加
background-size: 400% 400%可看清渐变是否真被固定住了

















