DEV Community

Fidel Leal
Fidel Leal

Posted on

Hiding HTML elements

After reviewing Codecademy's CSS courses, I found myself pondering the differences between display: none, visibility: hidden, and visibility: collapse. Here is what I discovered.

 

The use of display: none is pretty straightforward. When applied to an element, the browser does not render it. The space in the layout becomes available and all items on the page will behave as if the hidden element did not exist.

On the other hand, visibility: hidden turns off the display of an element while allowing it to keep occupying its space. Thus, the remaining items will still respect the hidden element's space in the page's layout.

Then there is visibility: collapse, which is a little more interesting. For most elements, this declaration works in the same way as display: none. The item will disappear and its space in the layout made available for other elements to occupy. However, with table and flex elements, the behavior depends on the browser we use.

Table elements with collapse will disappear from the page. Chrome and Firefox will remove the space occupied by the element as they do with display: none, but with one important caveat: surrounding rows and columns will maintain the exact cell dimension they had when the collapsed element was present. So, you can virtually eliminate a cell or column (and the space it occupies) without having the table automatically adjust its dimensions. Unless you are using Safari, which does not seem to treat collapse any differently from hidden πŸ‘ŽπŸ‘ŽπŸ‘Ž.

A nice table

A nice table.

display:none applied

display: none applied. Notice how cells automatically adjust their size.

visibility:hidden applied

visibility: hidden applied. Space is preserved and cells maintain their size.

visibility:collapse applied

visibility: collapse applied. Space is removed and cells maintain their size.

visibility:hidden in Safari

visibility: hidden in Safari.

visibility:collapse in Safari

visibility: collapse in Safari.

 

In the case of flex elements, most browsers will not differentiate between collapse and hidden. The one exception is Firefox. A flex item with collapse applied will be hidden, and its space freed in the main axis but not the cross-axis. Why? That remains an unsolved mystery... This StackOverflow question features a good set of examples1 showing how collapse works with flex items.


  1. The specific response with examples mentions Firefox and Edge as the two browsers where collapse makes a difference for flex elements. However, this answer is six years old, and I suspect it refers to pre-Chromium-based Edge. The current Edge browser renders visibility: collapse similarly to visibility: hidden. ↩

Top comments (1)

Collapse
 
heratyian profile image
Ian • Edited

Great overview. Different browsers sometimes have different rule interpretations. At least we don’t have to worry about internet explorer anymore πŸ˜›