cssgradient

How to do a linear gradient which fades to transparent, not white, in CSS?


I have this as a gradient currently:

background: linear-gradient(
  to right,
  rgba(var(--white-rgb), 1) 0%,
  rgba(var(--white-rgb), 0) 100%
);

With this, on the left side it fades to pure white, and on the right it fades to transparent. If you have images paginating left, then what this looks like is this:

The image here is dark gray (it could be any image, this is just a placeholder), and the content background is different colors depending on where the paginating image scroller is used (in this case it's light gray, but could be green, red, blue, or other unknown colors). We originally had the background always be white, so fading to pure white made sense. But now it doesn't look right.

How can I say "fade the underlying content to transparent" on the left? Basically, start from transparent gradient on the right, then fade the background content to transparent on the left. Is something like that possible?

Otherwise, I might need to tell the gradient in every random case what the background color is to fade into, which will take some heavy refactoring probably, so wondering if I can avoid going down that road.

ChatGPT said to try this:

mask-image: linear-gradient(
  to right,
  rgba(0, 0, 0, 0) 0%, /* Fully transparent on the left */
  rgba(0, 0, 0, 1) 100% /* Fully opaque on the right */
);

But that doesn't work, my DOM structure is something like this:

<div class="images">
  <div class="image-scroller">
    <div class="image-container">
      <img src="..."/>
    </div>
    <div class="image-container">
      <img src="..."/>
    </div>
    <!-- more -->
  <div>
  <div class="paginate-left"></div>
  <div class="paginate-right"></div>
</div>

I would add that mask on paginate-left, but it doesn't apply to the <img> way beneath it seems.


Solution

  • The relatively new property mask-image mdn allows you to define an image whose alpha channel (opacity) would be used to mask the element it is applied to. This image can be a gradient.

    body {
      background: green;
    }
    
    img {
      display: block;
      border: 1px solid black;
      width: 200px;
      height: 200px;
      mask-image: linear-gradient(to right, black 50%, transparent 100%);
    }
    <img src="https://picsum.photos/200" alt="an image">