使背景图像成为渐变

时间:2016-02-28 23:00:21

标签: html css

我正在尝试为CSS背景图片添加渐变。我发现了一堆其他与渐变背景相关的帖子,图像位于顶部,但我希望图像本身是一个渐变。我试过这个:

body {
margin: 0;
width: 100%;
height: 100%;
font-family: rexlia;
background-size: cover;
background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url(cubes.jpg) no-repeat;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url(cubes.jpg) no-repeat;
background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url(cubes.jpg) no-repeat;
background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url(cubes.jpg) no-repeat;
background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url(cubes.jpg) no-repeat;
background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url(cubes.jpg) no-repeat;

}

然而,所有这些都显示未修改的图像。这个snippit实际上来自另一个帖子,显然它起作用了。虽然不适合我。任何人都可以对此有所了解吗?感谢。

2 个答案:

答案 0 :(得分:2)

我猜这就是您使用的 代码,然后您省略了html元素100 %高,以便body也可以100%高。



html {
  height: 100%;
}
body {
  margin: 0;
  width: 100%;
  min-height: 100%;
  background-size: cover;
  background-image: linear-gradient(to bottom, rgba(255, 0, 0, .5) 0%, rgba(255, 0, 0, .5) 59%, rgba(0, 0, 255, 0.65) 100%), url(http://lorempixel.com/image_output/technics-q-c-640-480-2.jpg);
}




JSfiddle Demo

答案 1 :(得分:1)

如果您移除margin:0;它可以工作并且渐变条纹图像(因为该defaut边距主体开始填充html),或添加html{height:100%;}它可以工作。

如果没有在两个标签中设置,

html或正文背景混合在一起

进行一些测试,以便您可以看到并理解行为

body {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.75) 100%), url(http://lorempixel.com/300/200/abstract/10) center no-repeat;
  background-size: cover, cover;
}
html:hover body {
  margin: 4em;
  /* gradient is repeated and takes margin value as reference to repeat itself in html background */
}

如果正文有内容或有效高度固定,则其工作方式相同

body {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.75) 100%), url(http://lorempixel.com/300/200/abstract/10) center no-repeat;
  background-size: cover, cover;
}
html:hover body {
  margin: 4em;
  /* gradient is repeated body's height and keeps being repetead in html background*/
  height: 100px;

如果添加html,body {height:100%;},则body具有有效高度。

html, body {height:100%;}
body {
  background: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0, 0) 59%, rgba(0, 0, 0, 0.75) 100%), url(http://lorempixel.com/300/200/abstract/10) center no-repeat;
  background-size: cover, cover;
}

最后,如果你给html一个背景值,body将在其自身内部拥有自己的背景。

html{background:lime;}
body {
padding:2em;
  background: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0, 0) 59%, rgba(0, 0, 0, 0.75) 100%), url(http://lorempixel.com/300/200/abstract/10) center no-repeat;
  background-size: cover, cover;
}