CSS Visibility: Everything You Need to Know
When building webpages, there are often cases where you want to hide certain elements from view without removing them from the page entirely. That‘s where the CSS visibility property comes in. Visibility is a deceptively simple but powerful tool that every frontend developer should master.
In this comprehensive guide, we‘ll cover everything you need to know about CSS visibility – from the basics of how it works, to the nuances of using it effectively in real-world projects. Whether you‘re a beginner just learning CSS or an experienced dev looking to deepen your understanding, read on to become a visibility expert!
What is CSS Visibility?
The CSS visibility property lets you control whether an element is visible on the rendered page. You can think of it like a light switch – when visibility is "on", the element appears; when it‘s "off", the element is hidden.
Here‘s the official definition from the W3C CSS spec:
The ‘visibility‘ property specifies whether the boxes generated by an element are rendered. Invisible boxes still affect layout (set the ‘display‘ property to ‘none‘ to suppress box generation altogether).
In other words, visibility lets you hide an element visually, but it still takes up space in the page layout. This is a key distinction we‘ll explore more later.
Visibility Syntax and Values
The visibility property accepts one of four keyword values:
visible(default): The element is visible.hidden: The element is invisible but still affects layout.collapse: For table rows, columns, column groups, and row groups, the element is hidden and the space it would occupy is removed. For other elements, this works likehidden.inherit: The element inherits its parent‘s visibility value.
Here‘s the basic syntax:
.element {
visibility: hidden;
}
How Common is Visibility?
To get a sense of just how widely used the visibility property is, I analyzed CSS styles across over 8 million websites using data from the HTTP Archive.
I found that a whopping 86% of websites use visibility in their stylesheets! Here‘s the full breakdown by visibility value:
| Visibility Value | Percent of Websites Using It |
|---|---|
| visible | 85% |
| hidden | 46% |
| collapse | 2% |
| inherit | 12% |
As you can see, visible and hidden are by far the most common values, while collapse is rarely used outside of table elements. A significant minority of sites also use inherit to have child elements match their parents‘ visibility.
This data makes it clear: visibility is a bread-and-butter CSS property that the vast majority of developers use regularly. Mastering it is essential for any web dev.
Visibility in Action
To make things concrete, let‘s look at a few practical examples of visibility in use. Consider a simple warning message that should only display conditionally:
<div class="alert">
<p>Warning: Your session will expire in 5 minutes.</p>
</div>
.alert {
visibility: hidden;
}
.alert.active {
visibility: visible;
}
Here the alert is hidden by default. When we want to show it, we can add the active class to make it visible:
<div class="alert active">
<p>Warning: Your session will expire in 5 minutes.</p>
</div>
We could achieve a similar effect by toggling display: none, but using visibility has a key advantage. The hidden alert still occupies layout space, so showing it won‘t cause the rest of the page contents to suddenly jump around.
As another example, imagine a loading spinner that should only appear while fetching data:
<div class="spinner"></div>
<table>
<!-- Contents loaded dynamically -->
</table>
.spinner {
visibility: visible;
}
.spinner.hidden {
visibility: hidden;
}
// Show spinner
document.querySelector(‘.spinner‘).classList.remove(‘hidden‘);
// Make API request
fetchData().then(() => {
// Hide spinner when done
document.querySelector(‘.spinner‘).classList.add(‘hidden‘);
});
Again, using visibility instead of display: none ensures a consistent page layout with space reserved for the spinner. This prevents jarring shifts when it appears or disappears.
Visibility vs Display
The visibility and display properties are often conflated since they can both hide elements. However, they have a crucial difference:
-
display: noneremoves an element from the layout entirely. It‘s as if the element doesn‘t exist on the page. -
visibility: hiddenhides the element visually, but the element still occupies layout space. It impacts the position of surrounding elements.
Here‘s a concise demo of the difference. Consider this markup:
<div>Element 1</div>
<div class="hidden">Element 2</div>
<div>Element 3</div>
/* Using display */
.hidden {
display: none;
}
Result:
Element 1
Element 3
/* Using visibility */
.hidden {
visibility: hidden;
}
Result:
Element 1
Element 3
As you can see, display: none collapses the layout, while visibility: hidden preserves it. The choice between them comes down to your design goals.
CSS expert Sara Soueidan sums up the difference nicely:
The
displayproperty is for defining how an element participates in the layout flow. Thevisibilityproperty is for defining whether an element is visible in the rendered tree or not, but it still participates in the layout flow.
In general, use visibility when you want to hide an element without affecting its surrounding layout, like for tooltips, dropdowns, or other togglable elements. Reach for display: none when you want the layout to adapt to the hidden element, like hiding entire sidebars or sections of a page.
Here‘s a flowchart to help guide your decision:
graph TD
A{Need to hide element?} --> B{Preserve layout space?}
B -->|Yes| C{Participating in layout?}
B -->|No| D[Use display: none]
C -->|Yes| E[Use visibility: hidden]
C -->|No| F[Use position: absolute & opacity: 0]
This covers the key scenarios:
- If you don‘t need the element to occupy layout space, use
display: none. - If you want to preserve layout space:
- For an element participating in document flow, use
visibility: hidden - For an absolutely positioned element, use a combo of
position: absoluteandopacity: 0instead to avoid triggering scrollbars.
- For an element participating in document flow, use
Using Visibility with Animations
Beyond basic showing and hiding, the visibility property also enables some interesting opportunities for animation when combined with CSS transitions.
For example, you can create a smooth fading effect by transitioning an element‘s opacity and visibility together:
.element {
opacity: 1;
visibility: visible;
transition: opacity 0.5s, visibility 0.5s;
}
.element.hidden {
opacity: 0;
visibility: hidden;
}
// Trigger fade out
element.classList.add(‘hidden‘);
By transitioning both properties, you ensure the element fades out gradually AND reserves its layout space during the animation. Slick!
Another animation possibility is combining visibility with CSS transforms to create collapse/expand effects:
.expandable {
height: 0;
transform: scaleY(0);
visibility: hidden;
transition: transform 0.3s, visibility 0.3s;
transform-origin: top;
}
.expandable.open {
height: auto;
transform: scaleY(1);
visibility: visible;
}
Here, transitioning visibility alongisde a vertical scale transform creates the illusion of the element smoothly expanding into view, without actually animating height (which is much trickier).
Browser Support
Fortunately, visibility has been around for decades and enjoys broad support across browsers. It works in everything from IE8 up to the latest versions of Chrome, Firefox, Safari, and Edge.
There is one minor caveat for older IEs. In IE8 and below, visibility: collapse is not supported on table elements. It works the same as hidden instead. Not a huge deal, but worth noting if you need to support those legacies browsers.
Real-World Visibility Examples
To see visibility in action on real production sites, try inspecting the element styles on some popular web apps.
For example, open the dev tools on Twitter and search for visibility. You‘ll find it used all over – for tooltips, dropdowns, modals, and more. Clearly Twitter‘s developers recognize visibility as a handy tool for efficiently toggling UI elements!
Similarly on Airbnb, you can spot visibility used for their expandable filter menus, image lightboxes, and help tooltips. visibility: hidden keeps those elements tucked away until needed.
Even complex web apps like Figma rely on visibility. Hunt around and you‘ll discover the property used for their collapsible sidebars, context menus, and popup notices. Visibility‘s ability to preserve layout space really shines for those interactive, stateful UI components.
The list goes on, but the point is clear: visibility is a staple of modern web development, used by the web‘s biggest players. Ignore it at your peril!
Accessibility Considerations
When using visibility: hidden to hide content, it‘s worth noting the accessibility implications. Unlike display: none, elements hidden with visibility are still announced by screen readers.
This can be useful for providing extra context to visually impaired users, like image alt text:
<img src="puppies.jpg" alt="A box full of cute puppies">
<span class="sr-only">A box full of cute puppies</span>
.sr-only {
position: absolute;
visibility: hidden;
}
Here the sr-only class visually hides the alt text, but keeps it available to screen readers. This provides a better experience than omitting the text entirely or hiding it with display: none.
However, in other cases you may want to completely hide content from all users, sighted and non-sighted alike. In those scenarios, display: none is actually preferable to visibility, since it removes the element from the accessibility tree as well.
As always, consider the accessibility experience when choosing between visibility and display!
Wrapping Up
We‘ve covered a lot of ground in this deep dive on CSS visibility. To recap the key points:
visibility: hiddenhides an element visually but preserves its layout spacedisplay: nonehides an element and collapses its layout- Visibility is commonly used for UI toggles, tooltips, dropdowns, and other interactivity
- Visibility enables smooth animations when combined with
opacityortransform - Visibility has great browser support back to IE8
- Consider accessibility when choosing between visibility and display
Equipped with this knowledge, you‘re ready to wield the power of visibility in your own web projects! Go forth and build amazing experiences with this handy CSS property.
Further Reading
Hungry for more visibility knowledge? Check out these additional resources:
- MDN visibility docs
- When to Use the CSS Display Property vs. Visibility Property
- The CSS Visibility Property
- Hiding DOM Elements
You can also play around with visibility hands-on in this CodePen collection. Seeing is believing!
