DEV Community

Discussion on: A quick note on performance:

afif profile image
Temani Afif • Edited on

But opacity is a better choice --> but opacity:0 and display:none will lead to different results so we cannot really compare between both

danbamikiya profile image
Dan Bamikiya Author

It's nice you read the post Termani. Visibly opacity: 0 and display: none lead to the same results. In rendered content and accessibility tree, different results.
The subject of this post is on performance so opacity, display, visibility and hidden attribute can all be compared in terms of performance.

When the need for performance is priority there are other ways to achieve the behaviour display: none gives.
For example:

  1. If the idea is to hide an element visually for an animation, opacity can be used together with transform ( or just transform alone depends on what you want to achieve )
  2. clip-path: inset(100%); with clip: rect(0 0 0 0); and overflow: hidden; can be used. To even support screen readers add white-space: nowrap;
afif profile image
Temani Afif

You should probably make the article more focused on animation and in such case we cannot use display because it's not animatable so even for animation it's difficult to apply the comparaison.
I still disagree that both opacity:0 and display:none gives the same result. Even if you combine opacity with transform, the element will remain in flow and will still contribute to the layout while it's not the case when using display:none (the element is no more considered in the layout so the browser need to re-render the layout thus it's more expensive than opacity)
opacity and display may lead to the same visual result if and only if the element is out of the flow (position:absolute or position:fixed) and we disable the mouse interaction (using pointer-events:none because we can interact with an element having opacity:0). In such situation we can compare both but in a normal flow we cannot.

I understand the performance comparaison but it's like comparing the performance of a Car with a Plane. It's clear the the Plane is faster than a Car but both aren't used for the same purpose