Properly hiding elements

Last modified by Lucas Charpentier (Sereza7) on 2023/12/20 10:50

Hiding an element should be done with respects to the semantics. A reflection about the role of this element and how it can be used by multiple types of users should be undertaken.
Thereafter are described three ways to hide elements, based on what users it's hidden from.
Visually refers to users that interact with the content based on the visual rendering supported browsers would make.
Semantically refers to users that interact with the content based on what assistive technologies provide them. Those assistive technologies base their representation on semantics in the page.

Hiding visually and semantically

Examples

An element disappearing from the UI after a user interaction; a label or description only for screen readers, referenced via aria-labelledby or aria-describedby (see this WAI-ARIA practice about naming elements).

Solution based on CSS

Use the property and value: display: none.

Solution based on HTML

  • For inputs, use the attribute and value: type="hidden".
  • For others, use the boolean attribute: hidden 1.

Hiding visually and showing semantically

Examples

A label for an interactive element that would just clutter the visual UI.

Solution based on HTML

Use the class: sr-only. (abbreviation of “screen reader only”)

Hiding semantically and showing visually

This technique should only be used on an element that could be removed without changing the user experience in any other way than the presentation.

  • Example of proper usage: The avatar picture to display a ‘User’ entry in a table. It’s always paired with the name of the user, so it’s not an issue to hide it from assistive technologies. In this case it’s better, since the information is repeated in two elements.
  • Example of grey area use: A separator in a list. The separator can be seen as nothing but a blank space, but for the user it implies a ‘separation’ between two groups of list elements. This separation should be reflected on a semantic meaning, hiding the separator is not the best solution.
  • Example of a clear misuse: Hiding a picture used to illustrate a <p>. Accessible content is content that conveys the same meaning no matter the technology used to read it. The picture has a purpose and meaning, and hiding this from assistive technologies prevents AT users from getting the full experience.

Use only on leave nodes of the DOM tree because this technique does not hide the content but only the semantics of the node. If you want to hide more than a leaf node, it’s very probable that you should consider hiding it visually too. If it’s still not possible, using the aria-hidden attribute is the last resort.

Solution based on HTML

Use the attribute and value: role="presentation".

  1. ^ This means avoiding using a dedicated class such as .hidden.

Get Connected