Is it possible to animate a CSS mask-image?

Issue

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>

Solution

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

Answered By – Temani Afif

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published