This is an interesting question and one that initially surprised me.
Toggling the visibility of an element can be useful for lots of different scenarios. One situation that I commonly find useful is setting a UI container
visibility: hidden until some certain state for the container is reached and then setting
visibility: visible to show the container and its content.
Generally, we could just achieve this using the display property. However, using display will mean that the UI container and all its children will be removed from the page layout, which in most situations is exactly what we want. However, in some cases, it may be that we actually need the UI container to represent real space in the DOM and so using
display: none is not suitable.
A simple example of this might be positioning a UI container based on its rendered size and position compared to some other element (like a toolbar being positioned next to some highlighted text in an article). If we first added the toolbar to the DOM and then did these calculations, this would likely result in our toolbar jumping from one position to another. One way of avoiding this is to make sure that when we first add our UI container to the DOM, it is
visibility: hidden. We can then perform our positioning calculations and then toggle
There are other solutions such as using
position off-page which might achieve the same result, but I've always found using visibility as a great choice.
But there is a gotcha that we need to be aware of.
If an element's visibility is set to visible, then even if the parent's visibility is set to hidden, the element will still be visible.
Oh hang on, maybe that does make sense...
In some ways, even obvious. Unless an element has specifically set a style property to a different value, then it should inherit the value from its parent or ancestor. If the parent is
color: red, then if the child has no color property it will inherit
Visibility is no different to this.
We know that setting an element as
visibility: hidden allows the page to keep the layout with the element still taking up its required amount of space on the page.
So not so much of a gotcha...
Here is a little code lab to show how we can toggle the visibility on each of the three elements and visualize the behaviour that we have been discussing here.