There are 3 different properties you can use to hide an element with CSS.
While all 3 properties makes an element hidden, each property works in a slightly different way. Knowing the differences will make it easier for you to make the right choice.
Here’s a graphic summarizing what each property does:
In the table above, you can see if an element will:
- Collapse, meaning that it doesnt’t take up any space on the page.
- Respond to events, e.g. a click.
- Be included in the taborder, meaning it will receive focus when using the tab key.
- Be animatable, meaning that you can animate the transition between the visible and hidden state of the element.
As you can see, whenever you need the element to disappear completely and not take up any space, you should use display: none;
. If you want the element to have a transition or fade-in effect when becoming visible, you should use opacity: 0;
.
When an element with display: none;
is set to something else than none
, the element will take up its full width and height immediately, even when the element is not visible. So if you want to animate the width and height as well, you would have to use something like jQuery.