Elements can be hidden and shown by toggling the display
property. However, this is not animatable, so we often turn to opacity
. At opacity: 0
, the element is hidden, and with a nice transition
on that property, it can be faded in and out smoothly.
Yet, opacity
only hides visually, not technically: the element is still focusable and visible to screen readers. So, how can we fade an element while maintaining accessibility?
Enter visibility
Show archive.org snapshot
. It also hides elements, but differently from display
– and
it can be transitioned
Show archive.org snapshot
. It will not fade by itself (still toggles), but it is kind enough to always be visible
during transition. This makes it a perfect complement for opacity
. Just transition both of them:
opacity: 0
visibility: hidden
transition: all 100ms
&.-visible
opacity: 1
visibility: visible
When fading in, visibility
will immediately be set to visible
, allowing the opacity transition to be shown. When fading out, visibility
will remain visible
until the opacity transition is over. Thanks to visibility
, the hidden element is truly hidden and neither focusable nor visible to screen readers.
Alternatives
If you're starting your transition from JavaScript, you can give the element the
[inert]
Show archive.org snapshot
attribute. This will make the browser ignore input events and prevent focus.
In the future we will be able to
transition to display: none
Show archive.org snapshot
by using the transition-behavior: allow-discrete
property. This will delay the display
change until the transition ends. This is supported in
all browsers except Firefox
Show archive.org snapshot
.