You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让CSS线性渐变在指定高度后停止重复?

解决CSS线性渐变滚动重复及高度限制问题

问题分析

原代码的核心问题有两个:

  • background简写属性会覆盖之前设置的background-color和background-repeat,导致no-repeat不生效;
  • 未指定background-size,渐变会默认根据元素高度自适应,当页面高度超过渐变范围时就会重复,且小屏幕下无法完整显示渐变过程。

修正后的代码

html {
  height: 100%;
}
body {
  min-height: 100%;
  background-color: #F00;
  background-image: linear-gradient(
    180deg,
    #F00 0px,
    #0F0,
    #00F,
    #F00 3000px
  );
  background-repeat: no-repeat;
  background-size: 100% 3000px;
}

关键修改说明

  • 将background改为background-image:避免简写属性覆盖background-color、background-repeat等单独设置的属性;
  • 添加background-size: 100% 3000px:固定渐变的高度为3000px,宽度占满视口,确保渐变过程完整展示;
  • 设置html { height: 100% }:保证body的min-height:100%能正确继承高度,避免页面高度不足时渐变显示异常;
  • 保留background-color: #F00:当页面高度超过3000px时,超出部分会显示该红色背景,符合需求。

内容的提问来源于stack exchange,提问作者Evert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:41:01