css - 在背景图像上垂直堆叠 css 渐变(未覆盖)

标签 css background-image gradient

我有一张背景图片,其中第一行像素是纯色(这是一张风景照片)。我们的想法是将它放在页面底部,然后在它上面有一个 CSS 渐变,从页面顶部延伸,停在图像的高度。有很多教程展示了如何叠加/隐藏渐变,但它们都假定您想要一个整页渐变或渐变叠加在背景图像之上。

我现在拥有的是:

background: rgba(30, 53, 192, 1);

background: url("myimage.jpg") no-repeat center bottom, -moz-linear-gradient(top, #000 0%, #1E35C0 100%);
background: url("myimage.jpg") no-repeat center bottom, -webkit-gradient(linear, 0% 0%,0% 100%, from(#000), to(#1E35C0));
background: url("myimage.jpg") no-repeat center bottom, -webkit-linear-gradient(top, #000 0%,#1E35C0 100%);
background: url("myimage.jpg") no-repeat center bottom, -o-linear-gradient(top, #000 0%,#1E35C0 100%);
background: url("myimage.jpg") no-repeat center bottom, -ms-linear-gradient(top, #000 0%,#1E35C0 100%);
background: url("myimage.jpg") no-repeat center bottom, linear-gradient(top, #000 0%, #1E35C0 100%);

background-size: contain;

几乎了预期的效果。 CSS 渐变很好,图像在正确的位置,但我不知道如何使渐变以一种美观且响应迅速的方式停止在图像上方。我可以玩弄百分比,但同样,这只有在我知道图像有多高时才有效。

我知道这在 javascript 中可能相当容易,但我希望有一种干净的 CSS 方法来做到这一点。

最佳答案

假设您的图片的纵横比为 4:1(即高度是宽度的 25%),您可以这样做:

html, body {
  margin: 0;
  height: 100%;
}
body {
  background-color: #ccc;
  background-image: url("http://ima.gs/transparent/000/000/200%C3%9750-200x50.png")
                  , linear-gradient(to top, transparent 25vw, #fff 25vw, #00f 100%);
  background-repeat: no-repeat;
  background-position: center bottom;
  background-size: contain;
}

渐变中的 vw 单位表示视口(viewport)宽度的百分比。因此,如果背景图像将拉伸(stretch)视口(viewport)的整个宽度,并且其高度为其宽度的 25%,则其高度将等于 25vw,您可以从底部开始渐变 25vw,并在页面顶部结束.

http://jsfiddle.net/8a5L20h4/

关于css - 在背景图像上垂直堆叠 css 渐变(未覆盖),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275865/

相关文章:

html - 将背景图像放入带有伪元素的形状中

css - 在其他图形之前加载背景图像

html - 将背景图像带到前台。可能与否?

Swift - 使用渐变

python - 总结直方图中的 Nan

javascript - 浏览器中的半像素如何与 JavaScript clientWidth/clientHeight 关联?

asp.net - CSS 和 ASP.NET 控件

css - 如何使最后的文字淡出渐变背景?

css - 如何在 IE 和 Firefox 中使 textarea 的宽度相同?

angular - 网格系统中使用 Flex Layout 的最后一项的大小相同