10

I'd like to animate the "mask-position" property of a CSS mask image. The mask-image itself is a simple gradient, and my intended behavior is that by changing the value of the mask position, I can make the background object fade in from left to right. However, is it possible to animate this property? If not, is there a workaraound?

.header-image figure {
    mask-image: url("http://thehermitcrab.org/wp-content/themes/the-hermit-theme/images/gradient-mask-straight.png");
    animation: clip-fade 3s;
}

@keyframes clip-fade {
  0% {mask-position: 100% 0%;}
  100% {mask-position: 0% 0%;}
}

The HTML:

<div class="header-image">
<figure>
<img src="https://thehermitcrab.org/wp-content/themes/the-hermit-theme/images/footer/crab-footer-chalk-logo.png"/>
</figure>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Ben Viatte
  • 485
  • 1
  • 5
  • 16

1 Answers1

17

Not sure what kind of animation you want to perform but since it's a simple gradient no need to consider an image. Simply define the gradient and then you must define the size in order to correctly animate it.

Here is a basic example

.header-image figure {
  -webkit-mask-image: linear-gradient(90deg, #0000, #fff, #0000);
          mask-image: linear-gradient(90deg, #0000, #fff, #0000);
  -webkit-mask-size: 300% 100%;
          mask-size: 300% 100%;
  animation: clip-fade 3s infinite alternate;
}

img {
  max-width: 100%;
}

@keyframes clip-fade {
  100% {
    -webkit-mask-position: right;
            mask-position: right;
  }
}

body {
  background: red;
}
<div class="header-image">
  <figure>
    <img src="https://i.stack.imgur.com/lkGW7.png" />
  </figure>
</div>

Gradient used in mask works the same way as used in background so here is a related question to get more details about how to deal with the calculation: Using percentage values with background-position on a linear-gradient

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • It's perfect, many thanks!! Yes it's much better to define the gradient without an image. I had tried that before, but with no result (because my mistake was elsewhere) so I was just groping in the dark. My mistake was not to have defined "mask-size". Now it works as intended. – Ben Viatte Feb 23 '20 at 08:58