What is the purpose of using visibility: hidden; in css?

I’m learning about the visibility: hidden; function in css but I can’t find anything on google about why you would want to use that. Can anyone explain the benefit of using this code?

Visibility being set to hidden is essentially a slightly watered down version of display being set to none. Both make an element disappear visually, but the important distinction is that display: none; removes the element from the DOM entirely, meaning that it’s not taking up any space. As a result using display: none; can cause the layout to shift as an element has been removed so some other content may shift and resize. Often this is fine and intended behaviour, however sometimes you just want something to be invisible without actually changing the page or resizing content. That’s what visibility: hidden; does.

As for possible use cases, one that immediately comes to mind is any situation where you require multiple overlain objects. So imagine you’ve got an image “carousel”, where instead of rotating images they fade in and out. One way you could do this would by dynamically changing the src of the image tag when the previous image fades out. However another way you could do this would be to have all the images loaded in sitting on top of each other, but with all but one set to visibility: hidden;. This way the images are all loaded in at the start and ready to go but there’s no chance of the page breaking layout for a second when the image transitions.

This is another interesting use case where you have a drop-down menu that fades in and out. However it might be pertinent to ask “why does visibility matter here when opacity does the transition?” Well in this particular use case, we need the opacity transition to trigger but also have the element non-focusable when hidden. Therefore as shown in the last code block on that site, we require timing functions in the transitions to make sure that the element is unhidden then opacity animation triggers and vice versa. However while display: none; might have been the consideration it actually doesn’t work because it’s not considered an animatable property, meaning that we have no way of actually timing the display toggle. Thus visibility becomes the natural choice as you get the benefits of display: none; that you’d want for this situation, with the benefit that you can give it a timing function as it is allowed in the transition property.

I understand this is a lot of info and some of these examples might be unclear right now, but there is a lot of good situations where visibility specifically is required, mainly for the fact that visibility doesn’t affect the layout of the document when the element is hidden. Best way to figure it out is simply to build projects and discover ways it can help!


Thankyou so much for this!