The visibility property in CSS is used to control the visibility of elements. It allows you to show or hide elements without affecting the layout of the document.
There are several values for the visibility property, each serving different purposes. Understanding these values helps in creating more interactive and visually appealing web pages.
visibility: visible; - The default value. The element is visible.
.visible-example {
visibility: visible;
border: 1px solid black;
padding: 10px;
}
visibility: hidden; - The element is not visible, but it still takes up space in the layout.
.hidden-example {
visibility: hidden;
border: 1px solid black;
padding: 10px;
}
visibility: collapse; - For table rows, columns, column groups, and row groups, this value hides the element and removes it from the table layout. For other elements, it acts like visibility: hidden;.
.collapse-example {
visibility: collapse;
border: 1px solid black;
padding: 10px;
}
visibility: inherit; - The element inherits the visibility property from its parent.
.inherit-example {
visibility: inherit;
border: 1px solid black;
padding: 10px;
}
It is important to note the difference between the visibility and display properties. While visibility hides the element but maintains its space in the layout, display: none; removes the element entirely from the layout.
.visibility-example {
visibility: hidden;
border: 1px solid black;
padding: 10px;
}
.display-example {
display: none;
border: 1px solid black;
padding: 10px;
}
visibility: visible; - The element is visible:
.visibility-visible-example {
visibility: visible;
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
visibility: hidden; - The element is hidden but still takes up space:
.visibility-hidden-example {
visibility: hidden;
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
visibility: collapse; - The element is hidden and does not take up space (only applies to table elements):
.visibility-collapse-example {
visibility: collapse;
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
visibility: inherit; - The element inherits visibility from its parent:
.visibility-inherit-example {
visibility: inherit;
border: 1px solid black;
padding: 10px;
margin-bottom: 10px;
}
Here are some practical tips for using the visibility property: