csswill-change

How to use and how works CSS' will-change property?


I found CSS will-changeW3.org docs, MDN docs property (which already works in Chrome and is partiali supported by Firefox and Opera) but I'm not really sure how it works. Does anybody know something more about this mysterious thing?

I have just read that it allows browser to prepare for calculation over the element in the future. I don't want to misunderstand it. So I have a few questions.

  1. Should I add this property to the element class or its hover state?

    .my-class{
        will-change: 'opacity, transform'
    }
    .my-class:hover{
        opacity: 0.5
    }
    .my-class:active{
        transform: rotate(5deg);
    }
    

    OR

    .my-class{
        ...
    }
    .my-class:hover{
        will-change: 'opacity'
        opacity: 0.5
    }
    .my-class:active{
        will-change: 'transform'
        transform: rotate(5deg);
    }
    
  2. How can it increase a browser performance? Theoretically, when CSS is loaded, the browser already "knows" what will happen with each element, doesn't it?

If you can add any good example illustrating how to use it efficiently, I will be grateful :)


Solution

  • I won't copy paste the entire article here but here's a tl;dr version:

    Specifying what exactly you want to change allows the browser to make better decisions about the optimizations that it needs to make for these particular changes. This is obviously a better way to achieve a speed boost without resorting to hacks and forcing the browser into layer creations that may or may not be necessary or useful.

    How to use it:

    will-change: transform, opacity;
    

    How not to use it:

    will-change: all;
    
    .potato:hover {
      will-change: opacity;
      opacity:1;
    }
    

    Specifying will-change on hover has no effect:

    Setting will-change on an element immediately before it changes has little to no effect. (It might actually be worse than not setting it at all. You could incur the cost of a new layer when what you’re animating wouldn’t have previously qualified for a new layer!)