Emmanuel Akinfulubi

HTML and CSSPractical I

Visually hidden text for screen readers in CSS

7 Hide something visually but keep it for screen readers

hard

Remove an element from view without removing it from the accessibility tree, so a screen reader still announces it. Explain why the obvious answers are wrong.

Stuck? Three hints, smallest first
  1. 1. display: none and visibility: hidden both remove it from the accessibility tree too.
  2. 2. The standard recipe clips it to a single pixel and positions it absolutely so it takes no space.
  3. 3. Do not use width: 0; some screen readers skip zero-sized elements.

index.html

<h2 class="visually-hidden">Fares table</h2>
<p>Visible content. The heading above is announced but not shown.</p>

style.css

.visually-hidden {
  position: absolute;   /* takes no space in the layout */
  width: 1px;           /* not 0: some readers skip zero-sized elements */
  height: 1px;
  margin: -1px;         /* pull the last pixel out of view */
  padding: 0;
  border: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
9 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 7

test('it is taken out of the layout', declares(css, 'position', 'absolute'), true);
test('one pixel wide, not zero', declares(css, 'width', '1px'), true);
test('one pixel tall, not zero', declares(css, 'height', '1px'), true);
test('the last pixel is pulled off screen', declares(css, 'margin', '-1px'), true);
test('and clipped away', /clip-path\s*:/.test(css), true);
test('display none is NOT used', declares(css, 'display', 'none'), false);
test('visibility hidden is NOT used either', declares(css, 'visibility', 'hidden'), false);
test('zero width is avoided', declares(css, 'width', '0'), false);
test('there is visible content alongside it', hasTag(html, 'p'), true);

Output


      

The two negative assertions are the exercise. display: none and visibility: hidden both hide an element from screen readers as well as from eyes, so using either for a caption or a skip link means the people who needed it most get nothing. This recipe is what frameworks call .sr-only or .visually-hidden, and the 1px rather than 0 is deliberate: some readers skip elements with no size at all.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.