Hiding Content Responsibly
We’ve covered the idea of hiding things in CSS many times here, the most recent post being Marko Ilic’s “Comparing Various Ways to Hide Things in CSS” which did a nice job of comparing different techniques which you’d use in different situations. Hugo “Kitty” Giraudel has done something similar in “Hiding Content Responsibly” which looks at 10 methods—and even those, you could say, aren’t totally comprehensive.
Does this mean CSS is messy and incomprehensible? Nah. I feel like all the methods are logical, have good use cases, and result in good outcomes. Allow me to do a have a pretend conversation walking through my thought process here.
I need to hide this thing completely. For everyone.
No problem, that’s what the aria-hidden
attribute is for.
I need to hide this thing, but only hide it for screen readers, not visually. (For example, an icon that has no additional meaning for screen readers, as there is an accessible label nearby.)
No problem, use display: none;
.
I need to hide this thing, but only visually, not for screen readers. (For example, the contents of non-active tabs.)
No problem, use a .sr-only
class. That leaves it accessible but hides it visually until you remove that class.
Oops, I actually want to hide this thing visually, but I still want it to take up physical space, not collapse. (For example, say a button has a loading spinner icon that is only needed when performing an action. The size of the button should factor in the size of that icon all the time, not just when the spinner is visible. That way, there’s no layout shifting when that icon comes and goes.)
No problem, use transform: scale(0)
which will visually collapse it, but the original space will remain, and will leave it accessible to screen readers.
Oh nice, I could transition
the transform, too, I suppose. But actually, that transition
doesn’t fit my site well. I just want something I can fade out and fade in.
The opacity
property is transitional, so transition that between 0 and 1 for fades. The good news is that visibility
is also transitional. When fading out, use visibility: hidden
, and when fading in, use visibility: visible
to hide and unhide the thing from screen readers.
That’s not entirely comprehensive, but I find that covers 95% of hiding cases.
The post Hiding Content Responsibly appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.