The visibility
property is used to change the visibility of elements, i.e., it can show or hide elements. It does not lead to any change in the layout on hiding an element.
CSS
visibility: value;
The element hidden by this property still exists in the document and takes the same space as it would take if it were visible. If you want to remove an element completely from the document so that it does not take any space, then set the display
property to none
.
Values
visible
: Makes the element visible. This is the default value.
hidden
: Makes the element invisible, but the element still takes the same space and affects the layout of the document. Descendants of the element will be visible if they are set to visibility: visible.
collapse
: For table elements, it hides the row or column such that it does not occupy any space (as in display: none). However, the widths and heights of other rows and columns are still calculated as if the collapsed cells are present.
For all other elements, this value behaves the same as hidden
.
initial
: Sets the default value of the property.
inherit
: Inherits the value from parent element.
Examples
Look at the first example.
HTML
<h1>This is first heading</h1>
<h2>This is second heading</h2>
<h3>This is third heading. Notice that the second heading is hidden but still takes space.</h3>
CSS
h1 {
visibility: visible
}
h2 {
visibility: hidden;
}
h3 {
visibility: visible;
}
See the Pen visibility property example by Aakhya Singh (@aakhya) on CodePen.
In the above example, the second heading is given visibility: hidden which made the heading invisible, but it still takes the same space that it would have taken if it were visible.
Look at another example.
HTML
<p>This is a hidden paragraph with a child span element. <span>This is a visible span element inside a hidden paragraph.</span> This is the end of the paragraph.</p>
CSS
p {
visibility: hidden;
}
span {
visibility: visible;
}
See the Pen Visible child of hidden parent by Aakhya Singh (@aakhya) on CodePen.
As stated above, a child of a hidden element can be made visible by giving it visibility: visible. So, in the above example, the span element is made visible which is a child of the p element which is hidden.
The following example shows the second cell of a table getting collapsed on giving it visibility: collapse.
See the Pen Collapsing table cell using visibility: collapse by Aakhya Singh (@aakhya) on CodePen.
In the same way, entire table rows, columns, row groups or column groups can be collapsed.
Browser Support
This property is supported in all the major browsers. However, support for the value collapse
differs in different browsers.