CSS Visibility
Both display: none and visibility: hidden hide an element, but only one of them also removes the space it occupied.
There are two everyday ways to hide something in CSS, and the difference between them is whether the hidden element still takes up room in the layout. Choosing the wrong one leads to surprising gaps or unexpected shifts.
The key difference
Hiding but keeping the space
<!DOCTYPE html>
<html>
<head>
<style>
.placeholder {
visibility: hidden;
}
</style>
</head>
<body>
<p>Loading complete.</p>
<p class="placeholder">This text keeps its space.</p>
<p>Next line.</p>
</body>
</html>Hiding and removing the space
<!DOCTYPE html>
<html>
<head>
<style>
.removed {
display: none;
}
</style>
</head>
<body>
<p>First item.</p>
<p class="removed">This text is fully removed.</p>
<p>Last item.</p>
</body>
</html>When to use each
- Use visibility: hidden when you want the surrounding layout to stay exactly as it is, such as toggling a spinner in place.
- Use display: none to fully collapse the element, for example when hiding a menu that should not leave a gap.
- Remember that visibility: hidden elements are still in the document flow and read by some assistive tech, while display: none removes them from the accessibility tree.
Note: Neither property is truly private. The content is still in the page source, so never rely on hiding alone to protect sensitive information.
Note: For fade effects, animate the opacity property instead, since visibility and display cannot be smoothly transitioned on their own.