Improving Web Accessibility with Bootstrap's `.sr-only` Class

Learn how to make elements accessible to screen readers using Bootstrap's `.sr-only` class. This tutorial explains how to use this utility class to hide content from sighted users while ensuring it remains accessible to assistive technologies, enhancing website accessibility for visually impaired users.



Making Elements Accessible to Screen Readers with Bootstrap's `.sr-only`

Understanding Screen Readers and `.sr-only`

Screen readers are assistive technologies that help visually impaired users access web content. Bootstrap's `.sr-only` class is a utility class designed to hide elements from sighted users while keeping them visible to screen readers. This improves website accessibility by ensuring that all users can access important information.

Using `.sr-only`

The `.sr-only` class applies CSS styles that effectively hide an element from sighted users. It typically uses these styles:

  • position: absolute; (removes the element from the normal layout flow)
  • width: 1px; (makes the element extremely narrow)
  • height: 1px; (makes the element extremely small)
  • padding: 0; (removes any internal padding)
  • margin: -1px; (moves the element off-screen)
  • overflow: hidden; (hides any overflowing content)
  • clip: rect(0, 0, 0, 0); (clips the element completely)
  • white-space: nowrap; (prevents text from wrapping)
  • border: 0; (removes any border)

These styles effectively hide the element from sighted users while screen readers can still access and read the content.

`.sr-only-focusable` Class

Combining `.sr-only` with the `.sr-only-focusable` class makes the element visible when it receives focus (e.g., when a keyboard-only user tabs to it). This ensures that users who cannot see the element can still interact with it.

Using `.sr-only` as a Mixin (Sass/Less)

If you are using a CSS preprocessor like Sass or Less, it is common to define `.sr-only` and `.sr-only-focusable` as mixins for easier reusability and improved code organization. This allows you to include the necessary styles concisely within your codebase.

Example Sass Mixins

@mixin sr-only {
  /* .sr-only styles */
}

@mixin sr-only-focusable {
  /* .sr-only-focusable styles */
}