display: none vs opacity: 0 vs visibility: hidden
A short while ago I came across a tweet on the difference between display: none
and visibility: hidden
and how they compare to opacity: 0
. In this article, we will find out the answer to that question.
To get started, we will an example of 4 boxes to demonstrate each property. You can find the code on my CodePen (link below 👇)
display: none
- When you use
display: none
on an element, it will be thrown out of the render tree. In other words, it is removed from the document layout. - It won't consume any space. Other Elements would behave like the element did not exist.
- It will also turn off the display of all the child elements.
- Browser would not respond to any of the events on the element.
opacity: 0
- On using
opacity: 0
on an element will make it fully transparent. - It consumes space.
- The element is accessible using tab indexes and the content can be read by screen readers.
visibility: hidden
- Like
opacity: 0
, usingvisibility: hidden
would also make the element invisible but the browser would not respond to any of the events on the element. - It consumes space.
- It doesn't change the visibility of the children elements.
- The element would not be accessible through tab indexes.
Explore Further 🌌
- CodePen
- MDN Docs on display-box, opacity, and visibility
- Travis Nelson's Tweet
If you found this article helpful, I would be grateful for your support.
"Buy me some paneer curry"
I'd love to read your thoughts on this article!!!