Improving web accessibility ensures that all users, including those with disabilities, can interact with a website effectively. Below are five modern HTML and CSS code examples to enhance accessibility in any website or web application.
Many users rely on keyboard navigation or screen readers. A skip link allows them to bypass repeated navigation and go straight to the main content.
<a href="#main-content" class="skip-link">Skip to main content</a>
.skip-link {
position: absolute;
top: -40px;
left: 0;
background: #000;
color: #fff;
padding: 10px;
z-index: 100;
}
.skip-link:focus {
top: 0;
}
Why? Users navigating via keyboard or screen readers can jump directly to content without having to tab through navigation links.
Reference: WebAIM - Skip Navigation Links
Users navigating via keyboard need clear focus indicators to see where they are on the page.
button:focus, a:focus, input:focus {
outline: 3px solid #FFD700;
outline-offset: 3px;
}
Why? The default browser focus outline is often too subtle. This improves visibility for users with visual impairments.
Reference: MDN - CSS Focus Styles
Ensure text resizes properly for users with different vision needs.
html {
font-size: 100%; /* Allows users to change text size via browser settings */
}
p {
font-size: 1rem; /* Scales with user settings */
line-height: 1.5;
}
Why? This approach respects user preferences for text size and ensures readability.
Reference: W3C - Web Accessibility and Text Resizing
Forms need clear labels to help screen reader users understand the purpose of each field.
<label for="email">Email Address</label>
<input type="email" id="email" name="email" required>
Why? Labels explicitly associate text with input fields, making it easier for assistive technologies to interpret.
Reference: W3C - Labels and Instructions
ARIA (Accessible Rich Internet Applications) roles and attributes improve the usability of interactive elements.
<button aria-expanded="false" aria-controls="menu" onclick="toggleMenu()">Menu</button>
<nav id="menu" hidden>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
function toggleMenu() {
const menu = document.getElementById('menu');
const button = document.querySelector('button');
const isOpen = menu.hidden;
menu.hidden = !isOpen;
button.setAttribute('aria-expanded', isOpen);
}
Why? The aria-expanded
attribute informs screen readers whether the menu is open or closed, improving navigation for users with disabilities.
Reference: MDN - ARIA Attributes