Last Updated: February 25, 2016
·
8.616K
· zanona

How to not trigger browser repaint when opacity changes

By using Chrome Dev Tools options (Show paint rectangles) I have been able to find out that when changing opacity for hover states of an element, causes the browser to repaint the element:

div { opacity: 0; -webkit-transform: translateZ(0); }
div:hover { opacity: 1; }

but when using floating points for the opacity repaint won't be triggered improving page performance.

div.one { opacity: 0.01; -webkit-transform: translateZ(0); }
div.one:hover { opacity: 0.99; }

You can test it here (make sure that the option Show paint rectangles is enabled)

UPDATE

Check @darsain comment below and see what‘s wrong with this approach.

3 Responses
Add your response

Isn't it better to use RGBA and change only A value?

over 1 year ago ·

That's incorrect. Every time something visual changes there has to be a repaint. That's how you can see those changes - the bitmap you are looking at has to be modified, i.e. repainted.

What you are observing is that when you use opacity that is between 0 or 1, you introduce an alpha channel to the element. Chrome will try to optimize this by compositing this element on GPU. The GPU composited layers show up when the "Show composited layer borders" is enabled, but not in "Show paint rectangles", as latter is showing only stuff that is rendered by CPU.

Overall, using non floating opacity is definitely faster.

When elements has a 0 opacity, Chrome can just ignore it when painting. When it is 1, it will just paint. but when it's a floating point, it has to also paint what is behind the element, than composit it on GPU, apply alpha channel, and overlay it. That is a lot more costly than just "ignore" or "paint".

You are doing yourself a disservice and lowering the performance of your site by using floating opacity values when they are not needed.

over 1 year ago ·

@darsain, thanks for the heads-up man. I just figure out (the sad way, after my whole website crashed on iOS) that this and many other ways to “prevent” re-paint don't always necessarily mean, more performance. In any case I might update the tip pointing to your comment so more people learn about it.

over 1 year ago ·