What is the Difference Between visibility: hidden and display: none in CSS?
Both methods are used to hide elements on a page, but they are fundamentally different, therefore, we must differentiate between the two. When you set visibility
to hidden
on an element, it is like setting opacity to 0. The box model of the element is invisible but it still affects the layout. Space is still allocated to it.
When you use display: none;
, however, the element is completely removed from the document layout. This means you can't tell that there is an invisible element on the page. The document is rendered like the element doesn't even exist.
<style>
.invisible { visibility: hidden; }
.no-display { display: none; }
</style>
<!-- Space will be reserved for this element, however, it will be invisible -->
<img src="hero.jpg" class="invisible" />
<!-- Space won't be reserved for this element, it is completely hidden from the layout -->
<img src="hero.jpg" class="no-display" />
Note that when removing an element from the visible layout with either setting visibility
to hidden
, or display
to none
, the element will also get removed from the accessibility tree. This means that the element and all of its descendants will be invisible to screen readers too.
We must also point out that when we set an element invisible using visibility
, its descendants can be still visible when setting visibility
to visible
:
// I am set to hidden, but I still affect the layout
.hidden {
visiblity: hidden;
// Although my parent is invisible, I can still be visible
.visible {
visibility: visible;
}
}
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: