You would think that hiding content with CSS is a straightforward and solved problem, but there are multiple solutions, each one being unique.
Developers most commonly use
display: none to hide the content on the page. Unfortunately, this way of hiding content isn’t bulletproof because now that content is now “inaccessible” to screen readers. It’s tempting to use it, but especially in cases where something is only meant to be visually hidden, don’t reach for it.
The fact is that there are many ways to “hide” things in CSS, each with their pros and cons which greatly depend on how it’s being used. We’re going to review each technique here and cap things off with a summary that helps us decide which to use and when.
How to spot differences between the techniques
To see a difference between different ways of hiding content, we must introduce some metrics. Metrics that we’ll use to compare the methods. I decided to break that down by asking questions focused on four particular areas that affect layout, performance and accessibility:
- Accessibility: Is the hidden content read by a screen reader?
- Document flow: Will the hidden element affect the document layout?
- Rendering: Will the hidden element’s box model be rendered?
- Event triggers: Does the element detect clicks or focus?
Now that we have our criteria out of the way, let’s compare the methods. Again, we’ll put everything together at the end in a way that we can use it as a reference for making decisions when hiding things in CSS.
Method 1: The
We kicked off this post with a caution about using
display to hide content. And as we established, using it to hide an element means that the element is not generated at all. It’s in the DOM, but never actually rendered.
The element will still show in the markup, if you inspect the page you will be able to see the element. The box model will not generate nor appear on the page, which also applies …