This post will teach you the 3 ways to make elements invisible in CSS. Each one behaves differently and has it own use case. Let me introduce you to the display, visiblity and opacity properties.
CSS display property
Every element on a page is a box (rectangle). Display specifies behavior of this box and how to renders on page. There are many values that can be used (full list here), but there are just a few commonly used, e.g.:
We can use display property to hide element by setting its value to none. It’s important to know that when you set display:none; to an element, it won’t take space on screen and all its descendants are always going to be hidden. The elements is “removed” from document layout.
In the following example there are 3 boxes, the middle box is hidden.
This is how it’s rendered by browser:
CSS visibility property
The visibility property doesn’t have much values (see them here), in fact it’s not that commonly used. It’s different than display, because it hides element, but it doesn’t remove it from document layout. It means that while you can make element invisible by setting visibility: hidden; it will still take space on screen.
Let’s look at example, again 3 boxes, 2nd box is hidden. Note that I’ve also set the display property on each box, it’s needed to make the rendering box as small as possible.
As you can see on screenshot belowe, our element still takes screen space:
Visibility can be undone by children
In regards to children, they will be also hidden (by default), but it can be undone. So we can make child element visibile even when its parent is hidden. Let’s modify previous example to see it in action (added visibility to child in second box):
This is how it looks like in browser:
CSS opacity property
Opacity works in entirely different way. It sets transparency, so in addition to making elements invisible (100% transparency) you can make it partially transparent (more here).
Element with opacity is not removed from document layout, it takes space on screen (after all you can make it 90% transparent, so it still should be visible). All it’s children will also become transparent. Next examples hides element by setting opacity:0;.