CSS: The difference between display and visibility
March 1, 2013
CSS contains two properties that affect visibility. If you aren’t fully familiar with the difference, you might assumed the following were basically identical:
However, these two class definitions will do two very different things. The visibility attribute actually only affects the visibility of some content. That is, if the user will be able to view the content. The space that that content occupies however, is still held by that content. So, if a large block of text for example occupied a large space on the page, setting its visibility to hidden will only hide the text. The space it takes up still remains. This is quite useful for error messages that might pop up on your page. It also doesn’t create a jarring affect to the user once the content appears and restructures the layout of the page.
The display attribute works by actually removing the item from the DOM. When you set the display of an element to “none”, the browser will reorganize the content as though that item had never been there. This is quite useful for such things as collapsible menus that need to be removed from the page once they have ceased being useful. It can also help reclaiming page space once an elements content is no longer useful to the user.
It’s also good to note which of these jQuery uses in its
.hide() methods. If you’ve used it before, based on the above information you might have guessed that it affects the “display” CSS attribute and completely removes the element from the DOM. jQuery also add’s the additional functionality of
.toggle() which allows you to toggle between showing and hidden without having to query an element for its current state. jQuery also allows for fading and sliding animations when calling these functions, to make these elements slide and fade in and out of your page in a less jarring way they straight removal from the DOM.
Both attributes have their place in different situations. A general rule would probably be that to keep your highly valuable website space well utilized, only set visibility on very small, 10 px or less elements, otherwise your users might be seeing a lot of empty real estate on their website.