How do I hide an element visually but keep it accessible to screen readers using CSS?
Benjamin C
benjamin c profile pic

To hide an element visually but keep it accessible to screen readers, you can use CSS techniques that utilize theclip orposition properties. Here's a step-by-step explanation of how you can achieve this: 1. Usingclip property: - Apply the following CSS rules to the element you want to hide visually:

1
2
3
4
5
6
7
8
9
10
   .visually-hidden {
       position: absolute !important;
       clip: rect(1px, 1px, 1px, 1px);
       padding: 0 !important;
       border: 0 !important;
       height: 1px !important;
       width: 1px !important;
       overflow: hidden;
     }
     

Thevisually-hidden class can be applied to any element you want to hide visually but keep accessible to screen readers. 2. Usingposition property: - Alternatively, you can use theposition property to hide an element visually while keeping it accessible to screen readers. Apply the following CSS rules to the element:

1
2
3
4
5
6
7
8
9
   .visually-hidden {
       position: absolute;
       left: -9999px;
       top: auto;
       width: 1px;
       height: 1px;
       overflow: hidden;
     }
     

This approach moves the element outside the visible area by setting its position and dimensions to minimize its impact on the layout. By applying either of these CSS techniques, the element will be visually hidden from sight, but it will remain accessible to screen readers. Theclip property method uses a tiny rectangular clip area to hide the element, while theposition property method positions the element outside the viewport. These techniques are commonly used to hide elements like off-screen navigation menus, skip links, or visually redundant elements. They help improve accessibility by ensuring that screen reader users can access the content while maintaining a visually clean design. Remember to choose the technique that best suits your specific requirements and compatibility with different screen readers.