CSS Visibility


Visibility

An element can be displayed/hidden by using a property called as visibility. This property can be used to hide error messages which are displayed to the user only when required. It can also be used to hide answers of an assessment until the user selects an option. The values which the property can take are: visible, hidden, collapse, initial and inherit.

CSS visibility properties:

  • visible: It is the default value, and it makes the element visible.
  • hidden: It hides the element on which it is applied.
  • collapse: It is only applicable on the < tr>, < tbody>, < col>, and < colgroup> tags of a table. This value is used for removing any row or column but does not affect the layout of the table. The space that the row or the column took will now be available for other content. If you use collapse on any other tag or element, it renders as “hidden.”
  • initial: It is used for setting the property to its default value.
  • inherit: It is used for inheriting the property from its parent.

Key points to remember:

  • visibility: collapse is not supported in the latest browsers or is sometimes partially incorrect.
  • This might change the table layout if there is a nested table within the cells and those are collapsed, unless you specify the property explicitly on nested tables.

Example No.1:

<html> <html lang="en-US"> <style> h2.a { visibility: visible; } h2.b { visibility: hidden; } </style> </head> <body> <h1>Knowledge2life</h1> <h2 class="a">Knowledge2life website 1</h2> <h2 class="b">Knowledge2life website 2</h2> </body> </html>

OUTPUT:

Knowledge2life

Knowledge2life website 1

Example No.2:

<html> <html lang="en-US"> <style> table, td { border: 1px solid black; } tr.collapse { visibility: collapse; } </style> </head> <body> <h1>Knowledge2life</h1> <table> <tr> <td>website 1</td> <td>online</td> </tr> <tr class="collapse"> <td>website 2</td> <td>offline</td> </tr> </table> </body> </html>

OUTPUT:

Knowledge2life

website 1         |       online