When working on web development, you may come across a class called sr-only.
This is a very important class for accessibility (A11y).
Not displayed on the screen
Read aloud by screen readers
It is used to create "text that is invisible but exists."
In this article, I will explain why sr-only is necessary and how to use it in a way that is easy for beginners to understand.
What is sr-only?
sr-only (Screen Reader Only) is a class used to hide content visually while still conveying it to screen readers (text-to-speech software).
It is a staple in accessibility compliance, and similar utilities are provided in frameworks like Bootstrap and Tailwind.
Features of sr-onlyScreen display: Not displayed Screen reader: Read aloud
Although invisible to users, it remains in the DOM, so it has the following benefits:
It affects SEO
It does not break the HTML structure
It can convey meaning only to assistive technologies
are the benefits.
How sr-only works (CSS)
The CSS for a typical sr-only class is as follows.
.sr-only position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
Make the element a tiny 1px size
Clip it from the display area
Completely hidden using overflow: hidden
However, since it is not display: none, it can still be read aloud
In other words, it creates a state where it is "visually completely hidden, but programmatically present."
Why is sr-only necessary?
1. The problem where icons alone do not convey meaningFor example, while some people understand the meaning of a hamburger menu icon visually, it is just a symbol to a screen reader.
→ It is not accessible as is
Therefore,
<button> <svg aria-hidden="true">…</svg> <span class="sr-only">メニューを開く</span> </button>
By doing this, you can display only the icon on the screen while telling the screen reader "Open menu."
<nav aria-labelledby="main-nav-label"> <h2 id="main-nav-label" class="sr-only">メインナビゲーション</h2> … </nav>
Even if you don't want to display a heading visually, it is important for assistive technology to know "what this navigation is."
By using sr-only, you can strengthen the semantics without breaking the visual design.
3. Maintaining context for SEO as welldisplay:none and visibility:hidden are not recommended because they are also excluded from being read aloud. Since sr-only remains as a target for reading aloud, it has the advantage of conveying meaning for SEO purposes as well.
Summary of actual usage examples
1. Adding descriptions to icon buttons<button> <svg aria-hidden="true">…</svg> <span class="sr-only">検索を実行</span> </button>
<h2>製品一覧 <span class="sr-only">カテゴリー一覧ページの見出し</span></h2>
<nav aria-labelledby="nav-label"> <h2 id="nav-label" class="sr-only">サイト内メニュー</h2> … </nav>