Computer scienceFrontendCSSAdvanced features

Visibility

4 minutes read

Think of a website that has these two features: a menu that unfolds when you click on it, and a pop-up window with a hint that activates when you hover the cursor over it. What do the menu and the hint have in common? Both change the visibility of the element. When you think about how to hide elements or make them visible, it may seem quite difficult to implement. However, the CSS visibility property is actually quite easy to use. Let's study this property in more detail.

Syntax

The visibility property is intended to hide or show the element without changing the markup of the HTML document. You can set it to the following values:

  • visible is the default value, meaning that the element is displayed as visible.

  • hidden makes the element invisible.

  • collapse can hide rows and columns of a table, and the table will be reconstructed taking the missing elements into account. If you try to apply this value to something that is not a table element, the result will be the same as if you used hidden.

  • inherit will allow you to inherit the value of the parent element.

  • initial sets the property to its default value.

  • unset is basically a combination of the initial and inherit values. The unset keyword sets the property value as inherit if the property is inherited from the parent element; otherwise, the value is set as initial.

Examples of property usage

Take a look at an example of using the visibility property. Try to understand what happens in this code:

h1 {
  visibility: hidden;
}

In this example, it is specified that the <h1> element should be invisible.

Let's apply this to the following HTML code:

<h1>Chess online</h1>
<p>Start a new game</p>

This is the result that we will see in the browser:

Invisible heading and visible paragraph

Note that although the <h1> element is hidden, it can still be found in the HTML markup. You can use the developer tools (Ctrl+Shift+I or Cmd+Opt+I) to verify this:

Selected invisible heading on the page

Even if you hide elements using the visibility property, they remain in the markup. If you want to skip completely when rendering the document as if the element did not exist at all, then instead of using visibility, set the display property to the value none.

If you need more examples, check out the interactive page about the visibility property at MDN.

Conclusion

Skillful magicians can make objects appear on the stage or disappear completely. Now you can compete with them, as in this topic you have learned the property that changes the visibility of elements. Abracadabra.

226 learners liked this piece of theory. 7 didn't like it. What about you?
Report a typo