๐ What Is visibility?
The visibility property controls whether an element isvisible or hidden โ but unlike display: none, the element still **occupies space in the layout** even when hidden.
Note
โ Child elements may still become visible (special case!)
โ Useful for toggling UI elements without shifting layout
๐ฆ Syntax
visibility syntax
visibility: visible | hidden | collapse;๐ Values Explained
| Value | Description |
|---|---|
| visible | Default. Element is shown normally. |
| hidden | Element is hidden, but still takes up space. |
| collapse | Special: Used by table rows/columns โ space collapses. |
๐ฏ visibility vs display: none
| Property | Effect |
|---|---|
| visibility: hidden | Hides but reserves layout space |
| display: none | Removes element from layout completely |
๐ 1. Basic Example
Hide an element
.box {
visibility: hidden;
}The box is invisible but still pushes surrounding elements.
๐ 2. Toggle Visibility Without Reflow
No layout shift
.popup {
visibility: hidden;
}
.popup.show {
visibility: visible;
}Great for dropdowns, tooltips, hover effects, and transitions.
๐ 3. Visibility with Hover
Hover to show
.menu-item .submenu {
visibility: hidden;
}
.menu-item:hover .submenu {
visibility: visible;
}๐ 4. Child Visibility Override
If a parent has visibility: hidden, setting visibility: visible on a child **makes it visible again** โ unlike display: none.
Child override
.parent {
visibility: hidden;
}
.parent .child {
visibility: visible;
}Note
๐ 5. visibility: collapse for Tables
collapse is meaningful in table layouts. It hides rows/columns and collapses space.
Collapse table row
tr.hidden-row {
visibility: collapse;
}๐ 6. Animating Visibility (with opacity)
visibility itself cannot animate smoothly, but it's often paired with opacity.
Smooth fade
.fade {
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease;
}
.fade.show {
opacity: 1;
visibility: visible;
}๐งช Real-World Examples
1๏ธโฃ Tooltip Show/Hide
Tooltip example
.tooltip {
visibility: hidden;
opacity: 0;
transition: 0.2s;
}
.button:hover .tooltip {
visibility: visible;
opacity: 1;
}2๏ธโฃ Dropdown Menu
Dropdown
.dropdown ul {
visibility: hidden;
}
.dropdown:hover ul {
visibility: visible;
}3๏ธโฃ Hiding Items Without Breaking Layout
Reserved space
.label {
visibility: hidden;
}โ ๏ธ When NOT to Use visibility
- โ For removing elements โ use display: none
- โ For layouts (Grid/Flexbox already handle spacing)
- โ For accessibility hiding โ use hidden attribute or aria-hidden
๐ฅ Summary
The visibility property controls whether an element is visually shown while keeping or removing its layout space. It's perfect for dropdowns, tooltips, transitions, and situations wheredisplay: none would cause layout shifts.
Learn more โMDN Docs ๐