【问题标题】:Gradient background not stretching to cover top to bottom渐变背景不拉伸以覆盖从上到下
【发布时间】:2017-07-03 13:50:23
【问题描述】:

我正在尝试实现渐变色背景。这是相关的代码。

#grad {
  background: -webkit-linear-gradient(red, white, blue);
  background: -moz-linear-gradient(red, white, blue);
  background: -o-linear-gradient(red, white, blue);
  background: linear-gradient(red, white, blue);
}
<body id="grad">...</body>

但是,这只会覆盖到我的导航栏的背景,然后背景会重复出现。我尝试了以下代码:

#grad {
  background: -webkit-linear-gradient(red, white, blue);
  background: -moz-linear-gradient(red, white, blue);
  background: -o-linear-gradient(red, white, blue);
  background: linear-gradient(red, white, blue);
  height: 100%;
  width: 100%;
  left: 0px;
  top: 0px;
  z-index: 0;
  position: absolute;
}
<body id='grad'>...</body>

背景就消失了。请帮忙。

【问题讨论】:

    标签: css background gradient


    【解决方案1】:

    如果您不希望它重复,只需在线性渐变的末尾添加 no-repeat。

    例如:

    background: linear-gradient(red, white, blue) no-repeat;
    

    然后将你的身高设置为任何你想要的。

    如果你想让它的高度 = 100%,那么只需使用以下 css 制作一个 div 标签。

    background: -webkit-linear-gradient(red, white, blue) no-repeat;
    background: -moz-linear-gradient(red, white, blue) no-repeat;
    background: -o-linear-gradient(red, white, blue) no-repeat;
    background: linear-gradient(red, white, blue) no-repeat;
    position: absolute;
    height: 100%;
    width:100%;
    left:0;
    top:0;
    

    你不想让身体成为绝对的。但是话又说回来,如果您要使用 div 标签以第二种方式执行此操作,则无需重复。

    【讨论】:

    • 我尝试添加 no-repeat,但背景仍然停止直到导航栏。我尝试添加 height: 100%,但没有任何变化。
    • 再试一次,但使用 Div 标签。不要在 body 标签上使用 'position:absolute'。
    【解决方案2】:

    body 将只有内容的高度,即使您将高度设置为 100%,浏览器也必须知道 100% 的什么

    在这种情况下,父元素 html 需要设置 100% 的高度。

    html {
      height: 100%;
    }
    
    #grad {
      background: -webkit-linear-gradient(red, white, blue);
      background: -moz-linear-gradient(red, white, blue);
      background: -o-linear-gradient(red, white, blue);
      background: linear-gradient(red, white, blue);
    }
    <body id="grad"></body>

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 2019-12-28
      • 2011-05-16
      • 1970-01-01
      相关资源
      最近更新 更多