Tuesday, 12 February 2013

CSS: visibility: hidden vs display: none


Writing for the web thought becomes more complicated everyday. It goes down to the fact that I've wrote more than 380 posts since July 2010 and thinking about new things to talk about is getting harder and harder. However, some times a short conversation with a friend or a colleague might ignite a sparkle and might give me new ideas for a short post like the following.

I was in fact talking with a friend when it came to my mind that the difference between visibility and display properties in CSS is some times completely missed. Specifically, the difference between visibility: hidden and display: none.
The point is not that complicated, so in just a few words we are going to see the difference, and we are going to explore when to use visibility instead of display.

The situation
We have a DOM element in our page and we want it to "not be shown". The way we are going to make it invisible, is indeed affecting our whole page.
Usually, we use two CSS properties: visibility and/or display. But which one is better? Do they have the same effect on the page?
First thing: there's no better property. There must be a reason why we have two different properties which do the same thing.
Second: they apparently do the same thing, but they have different effect on the page.

Visibility: hidden
We can set visibility to hidden or display. The two values have obviously the opposite effect: the first hides the element, the second makes the element visible.
The point here is that the element - even when hidden - will always take up space. So, if we consider an element with a specific height and width, it will always take up that space - even when hidden.
It means that if we have, for example, three elements in a row, and we hide the second, the first and the third won't get together at all - the space between them will stay the same. The hidden element stays in the normal document flow.

Display: none
I'm sure now you know what happens when we use the display properties.
When we set it to none, the element is someway removed from the document flow and the surrounding elements will collapse, taking the space that was once taken by the hidden element.
The difference is not that small. It is indeed a big difference, and it heavily affects the document flow.

As you can see it's quite redundant for me to say when to use one property against the other. It really goes down to what we need. Usually, when we want to make an element disappear, we don't really want to leave a blank space. In fact, leaving a blank space is often the same as not hiding the element.

I hope you find the post useful, Leave your thought in the comments section below!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.