Back to topics

Difference between display:none and visibility:hidden

I remember an interview a long time ago when the interviewer asked me if I knew the difference between display:none (hereinafter referred to as dn) and visibility:hidden (hereinafter referred to as vh).

The most intuitive answer is, of course: both will hide the element; dn does not occupy space, while vh does occupy space.
Today, while reviewing reflow and repaint, I learned:

  1. vh occupies space so it does not trigger reflow, hence it performs better than dn.

  2. Moreover, for child elements, all child elements under dn are invisible; child elements under vh can be made visible by individually setting visibility:visible.

  3. From a performance perspective, vh is superior to dn, so whenever possible, vh is preferred.

What is Reflow (from AI)

Reflow is a part of the web page rendering process, specifically the process where the browser recalculates the geometric properties of elements (such as position and size) to reconstruct the render tree. This process may be accompanied by Layout and Painting. When changes to certain elements on the page affect the layout of surrounding content, reflow is triggered.

There are many situations that trigger reflow, such as:

  • Changes in element dimensions, such as dynamic adjustments to width, height, margins, padding, etc.

  • Page rendering initialization or browser window resize, requiring layout recalculation.

  • Changes in DOM structure, such as adding or removing visible DOM elements.

  • CSS style changes, especially those that affect element layout, such as modifications to display, position, float, etc.

  • Computing properties like offsetWidth, offsetHeight, clientWidth, clientHeight, getComputedStyle(), which may force the browser to perform reflow to get the latest data.

Reflow is a relatively time-consuming operation, especially on complex pages; frequent reflow can slow down user interface responsiveness and affect user experience. Therefore, when developing high-performance web applications, operations that trigger reflow should be minimized.