问题
I want to do this essentially in CSS:
div {
background: linear-gradient(to top, rgba(255,0,0,0), rgba(255,0,0,1), rgba(255,0,0,0));
width: 1000px;
height: 1000px;
}
<div>hello</div>
But instead of a color, I want to gradient-fade-in-and-out a background image, like this:
background: linear-gradient(to top, transparent, url(/myimage.png) repeat, transparent);
How to accomplish this in CSS, or if it's not possible in CSS, in JS.
My image is a seamless texture, so maybe that might factor into the equation since it is repeated. I also want to set the background-size
to different sizes to figure it out, so if you could specify that too that would be nice.
回答1:
You can consider mask to do this. You can specify the same properties as background thus you can easily define your gradient.
.box {
width: 1000px;
height: 1000px;
position:relative;
z-index:0;
}
.box:before {
content:"";
position:absolute;
z-index:-1;
top:0;
left:0;
right:0;
bottom:0;
background:url(https://picsum.photos/id/42/10/10);
-webkit-mask-image:linear-gradient(to top, transparent, #fff, transparent);
mask-image:linear-gradient(to top, transparent, #fff, transparent);
}
<div class="box">hello</div>
Or you can simulate this using multiple background. You will not have transparency but you will have better support:
.box {
width: 1000px;
height: 1000px;
background:
linear-gradient(to top,#fff, transparent, #fff),
url(https://picsum.photos/id/42/10/10);
}
<div class="box">hello</div>
来源:https://stackoverflow.com/questions/57245123/how-to-do-equivalent-of-a-linear-gradient-with-opacity-on-a-seamless-background