Search code examples
cssbackground-imagelinear-gradients

How to apply equivalent of linear-gradient with opacity on edges of non-repeated image


Like How to do equivalent of a linear-gradient with opacity on a seamless background image in CSS, but instead of a seamless background image, just a regular old image. How to do the same thing? Right now when I try it on a non-repeated background image the whole image is covered in the gradient.

div {
  width: 1000px;
  height: 1000px;
  background:
    linear-gradient(to bottom, #fff, transparent) top/5% 32px no-repeat,
    linear-gradient(to top, #fff, transparent) bottom/5% 32px no-repeat,
    url(https://picsum.photos/id/984/1000/1000) no-repeat;
  background-size: cover;
}
<div></div>

What I have there (above) is incorrect, the image is all covered under the gradient while I just want the edges (top and bottom) like 32px covered.


Solution

  • move cover to only the image or it will get apply to gradient and will override the 5% 32px

    div {
      width: 1000px;
      height: 1000px;
      background:
        linear-gradient(to bottom, #fff, transparent) top/100% 32px no-repeat,
        linear-gradient(to top, #fff, transparent) bottom/100% 32px no-repeat,
        url(https://picsum.photos/id/984/1000/1000) center/cover no-repeat;
    }
    <div></div>

    Or specify 3 values on the background-size

    div {
      width: 1000px;
      height: 1000px;
      background:
        linear-gradient(to bottom, #fff, transparent) top,
        linear-gradient(to top, #fff, transparent) bottom,
        url(https://picsum.photos/id/984/1000/1000);
      background-size:100% 32px,100% 32px,cover;
      background-repeat:no-repeat;
    }
    <div></div>