CodeBlanks Logo Icon CodeBlanks

Sr-only technique

CSS course · Advanced · Lesson 31/52

Learn the visually hidden technique for screen readers.

What is sr-only?

When you want to hide an element visually but keep it available to a screen reader, use the sr-only technique. It moves the element off-screen or shrinks it to 1 pixel; sighted users do not notice it, but screen readers still read it aloud.

The most common use is icon-only buttons. You add a "Close" text with sr-only next to a close icon; sighted users see the icon, screen readers say the text.

A solid sr-only form

A robust sr-only form combines several declarations: position: absolute, width: 1px, height: 1px, padding: 0, margin: -1px and overflow: hidden. The most critical declaration is clip: rect(0, 0, 0, 0) or its modern counterpart clip-path: inset(50%).

The element shrinks to 1 pixel and gets clipped; the clickable area stays intact. The negative margin pulls the element off-screen so the layout does not shift.

Exercise Write the .sr-only class

Write a declaration block for the .sr-only selector. Include these declarations: position: absolute, width: 1px, height: 1px, overflow: hidden and clip: rect(0, 0, 0, 0). Place each declaration on its own line.

Show example solution
/* write the sr-only class */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
}

Test yourself

  1. When do you use sr-only?

    • To add screen reader text to an icon-only button
    • To hide a paragraph from both sighted users and screen readers
    • To enlarge an image to fill the page
    • To shrink a heading's font size
    Show answer

    To add screen reader text to an icon-only button — Correct. Icon buttons get hidden text with sr-only; sighted users see the icon, screen readers say the text.

  2. Write the clip declaration

    .sr-only {
      position: absolute;
      width: 1px;
      height: 1px;
      ____;
      overflow: hidden;
    }
    Show answer
    .sr-only {
      position: absolute;
      width: 1px;
      height: 1px;
      clip: rect(0, 0, 0, 0);
      overflow: hidden;
    }
  3. Match the sr-only declarations

    position: absolute
    Out of page flow
    width: 1px
    1 pixel width
    clip: rect(0,0,0,0)
    Clipping rectangle
    overflow: hidden
    Hide overflow

All lessons in Advanced