Sub topic 13
Accessibility considerations
This chapter assumes you can build a Lightning web component (HTML template, JavaScript class, CSS file). It also assumes you have used lightning-input, lightning-button, lightning-card and lightning-datatable from the earlier chapters. Here you will learn what base components already do for accessibility and what you still have to supply yourself.
Why base components help, and where they stop
Base components are built to follow accessibility standards. A lightning-input renders a real <input> element, connects it to its label, and handles keyboard focus. A lightning-button renders a real <button>. You get these behaviors without writing ARIA attributes (the aria-* attributes that describe an element to assistive technology such as screen readers).
Base components cannot know what your content means. They need you to provide:
- Text labels that describe each field.
- Alternative text for icons that carry meaning.
- A logical reading and focus order.
- Error messages that a screen reader can announce.
- Sufficient color contrast when you override styles.
The rule of thumb: use the attributes the component gives you for accessibility before you reach for custom ARIA or custom markup.
Labels on form fields
Every input needs a label. Most input components make label a required attribute. If you omit it, the component logs a console warning and the field has no accessible name, so a screen reader announces only "edit text".
<template>
<lightning-input
label="Email address"
type="email"
value={email}
onchange={handleEmailChange}
></lightning-input>
</template>Sometimes the design calls for no visible label, for example a search box next to a magnifier icon. Do not delete the label. Keep it and hide it visually with the variant attribute:
<template>
<lightning-input
type="search"
label="Search contacts"
variant="label-hidden"
value={searchKey}
onchange={handleChange}
></lightning-input>
</template>With variant="label-hidden", the label is removed from the screen but remains available to screen readers.
Placeholders are not labels
The placeholder attribute disappears once the user types, and many screen readers treat it inconsistently. Use it only as a hint for format, such as placeholder="[email protected]", and always keep label as well.
Required fields and field-level help
Use required to mark a field as mandatory. The component adds a visual asterisk and sets the correct ARIA state. Use field-level-help for short guidance that a user can open from an info icon.
<template>
<lightning-input
label="Phone"
type="tel"
required
field-level-help="Include the country code for non-US numbers."
value={phone}
onchange={handlePhoneChange}
></lightning-input>
</template>Alternative text for icons and images
Icons come in two kinds, and each needs different handling.
- Decorative icons add nothing the text does not already say. They should be hidden from assistive technology.
- Meaningful icons convey information on their own, such as a warning symbol with no text beside it. They need alternative text.
lightning-icon takes an alternative-text attribute. Set it for meaningful icons. For decorative ones, leave it out so the icon is not announced.
<template>
<!-- Meaningful: nothing else says this is a warning -->
<lightning-icon
icon-name="utility:warning"
alternative-text="Warning"
variant="warning"
size="small"
></lightning-icon>
<!-- Decorative: the adjacent text already says "Account" -->
<lightning-icon icon-name="standard:account" size="small"></lightning-icon>
<span class="slds-var-m-left_x-small">Account</span>
</template>Write alternative text that states the purpose, not the picture. "Warning" is better than "Yellow triangle".
Icon-only buttons
A button with only an icon has no visible text, so it needs an accessible name. Use lightning-button-icon and set alternative-text. The component also uses this text as a tooltip.
<template>
<lightning-button-icon
icon-name="utility:delete"
alternative-text="Delete contact"
title="Delete contact"
onclick={handleDelete}
></lightning-button-icon>
</template>If you leave out alternative-text, a screen reader announces only "button". The user then cannot tell a delete button from a save button.
Keyboard access
Users who cannot use a mouse move through a page with the Tab key and activate controls with Enter or Space. Base components support this by default. Problems appear when you replace them with plain elements.
A <div onclick={handleClick}> is not focusable and does not respond to the keyboard. Prefer lightning-button, or a native <button>, for anything that acts when clicked.
If you need a custom focusable element, you must supply all of the following yourself:
- A
tabindexso it can receive focus. - A
rolethat describes it, such asbutton. - Handlers for Enter and Space, not only for clicks.
Using a real button avoids all three steps.
Tab order and `tabindex`
Keep the DOM order the same as the visual order, so Tab moves in a predictable sequence. Use tabindex="0" to add an element to the natural order and tabindex="-1" to make it focusable by script only. Avoid positive values such as tabindex="3". They override the natural order and are hard to maintain.
Moving focus on purpose
After an action that changes the page, such as opening a dialog, move focus to the new content. Base components expose a focus() method, which you call from JavaScript:
import { LightningElement } from 'lwc';
export default class FocusExample extends LightningElement {
showForm = false;
handleShow() {
this.showForm = true;
}
renderedCallback() {
if (this.showForm) {
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
}
}
}renderedCallback runs after every render, so this example calls focus() on each re-render while the form is shown. In real code, use a flag so you focus only once, or users who type will lose their place.
Errors and validation
Color alone must never be the only sign of an error. Base components show an error message as text and link it to the field, so screen readers announce it. To use this behavior, rely on the component's own validation attributes and methods.
<template>
<lightning-input
label="Quantity"
type="number"
min="1"
max="10"
message-when-range-underflow="Enter a quantity of at least 1."
message-when-range-overflow="Enter a quantity of 10 or less."
onchange={handleQuantityChange}
></lightning-input>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>import { LightningElement } from 'lwc';
export default class QuantityForm extends LightningElement {
quantity;
handleQuantityChange(event) {
this.quantity = event.target.value;
}
handleSave() {
const input = this.template.querySelector('lightning-input');
if (input.reportValidity()) {
// Safe to save
}
}
}reportValidity() returns true or false and displays the error messages on the field. For a custom rule, call setCustomValidity('Your message') on the input, then reportValidity(). Call setCustomValidity('') to clear the error again.
Inside lightning-record-edit-form, include lightning-messages. It displays server-side errors in a region that assistive technology can read.
Structure and headings
Headings let screen reader users jump through a page. lightning-card renders its title as a heading-level element for you, which gives each card a landmark. When you add your own headings, use real heading elements (<h2>, <h3>) in a sensible order, and use SLDS classes such as slds-text-heading_medium to change appearance. Do not choose a heading level for its size. Choose it for its place in the outline, then style it.
Use lightning-formatted-text and similar components to display values, and use semantic elements (<ul>, <li>, <table>) for lists and tables you build by hand.
Data tables
lightning-datatable renders a real table with row and column semantics, keyboard navigation inside the grid, and sortable column headers. You help it by providing:
- Clear
labelvalues for every column, because these become the column headers. - A unique
key-field, so that row updates keep the user's position. - An
aria-labelor similar naming on the surrounding region when a page has more than one table.
When you hide the checkbox column with hide-checkbox-column, make sure the user still has a way to act on a row, such as a row action menu with clear labels.
Contrast and styling
SLDS colors meet contrast guidelines in their default state. When you apply styling hooks or custom CSS, you take over that responsibility. Check that text has at least a 4.5:1 contrast ratio against its background. For large text and interface boundaries, 3:1 is the minimum.
lightning-button {
--slds-c-button-brand-color-background: #0b5cab;
--slds-c-button-text-color: #ffffff;
}White text on #0b5cab is a high-contrast pairing. A pale blue background with white text would fail. Test with a contrast checker before you ship a custom color.
Also never remove the focus outline. If you override it, replace it with a visible alternative.
Shadow DOM and ARIA references
Attributes such as aria-labelledby and for refer to an element by id. Because of shadow DOM, an id in one component's template cannot be found from another component's template. In practice this means you cannot point a base component's aria-labelledby at an element in your own template. The attributes that base components provide, such as label, alternative-text and aria-label, work around this. Prefer them. Within your own template, references between elements that sit in the same template work normally. LWC rewrites the id values at render time, so do not rely on the exact string in a query selector. Use this.template.querySelector with a data-id or a class instead.
A quick audit checklist
Before you ship a component, check the following:
| Check | What to look for |
|---|---|
| Labels | Every input has a `label`, using `variant="label-hidden"` if it must not show |
| Icons | Meaningful icons have `alternative-text`; decorative ones do not |
| Icon buttons | `lightning-button-icon` has `alternative-text` |
| Keyboard | You can reach and use every control with Tab, Enter and Space |
| Focus | Focus moves to new content, and the outline stays visible |
| Errors | Messages are text, shown through `reportValidity()` or `lightning-messages` |
| Contrast | Custom colors meet 4.5:1 for text |
| Headings | Heading levels follow the page outline |
Automated tools such as the browser's built-in accessibility inspector or axe catch many of these problems. They cannot judge whether your alternative text makes sense, so also try your component with the keyboard alone and with a screen reader.
Exercise
A teammate builds a toolbar with <lightning-button-icon icon-name="utility:refresh" onclick={handleRefresh}></lightning-button-icon>. A screen reader announces only "button". What is missing, and what attribute fixes it?
Show answer
The button has no accessible name. Add alternative-text="Refresh" (and optionally title="Refresh") so assistive technology announces what the button does.
Exercise
Your design shows a search box with only a magnifier icon and no visible label. How do you keep it accessible with lightning-input?
Show answer
Keep the label attribute (for example label="Search contacts") and add variant="label-hidden". The label is hidden visually but still available to screen readers. Do not replace the label with placeholder.
Exercise
A custom brand button uses white text on a light blue background and the contrast ratio is 2.5:1. What must you do, and what minimum ratio applies to normal text?
Show answer
Change the colors so the contrast ratio is at least 4.5:1 for normal text, for example by using a darker background. Verify the result with a contrast checker.