How to Create an Accessible Search Bar Without a Label

JD Brewer-Hofmann
3 min readNov 12, 2020

If you’re looking to build a search bar with no label, this is the move

<form role='search'>
<label for="searchBar" class="sr-only">Search Term</label>
<input id="searchBar" type="text" placeholder="Search Term">
<button>Search</button>
</form>
/* CSS */
.sr-only {
position: absolute;
left: -10000px;
top: auto;
width: 1px;
height: 1px;
overflow: hidden;
}

Our CSS sets the label way off the screen, which doesn’t bother screen readers, but leaves you with a visually simple search input. Notice how the height and width are set to 1px each, if you were to set each to 0px the screen reader would skip over them entirely, so keep them at 1px. Overflow is hidden so if you wrote a long label title, which you definitely shouldn’t, it wouldn’t end up on the screen. Using a placeholder we can convey our input’s functionality to sighted users, while maintaining all the accessibility that comes standard with semantic html.

Here is the same option but written in JSX for React purposes

<form role='search'>
<label htmlFor="s" className="sr-only">Search Term</label>
<input id="s" type="text" name="search" placeholder="Search Term"/>
<button>Search</button>
</form>

This is functionally the same in react, take note of the use of htmlFor=”s”, for is a reserved name in JSX just like class, so remember to use htmlFor.

Second option:

<form role='search'>
<input id="searchBar" type="text" placeholder="Search Term" title="Search Term">
<button>Search</button>
</form>

The title attribute functions as a label when no label is present, you might not want it, but it comes stock with a tool-tip when you hover over the input for a second.

Last option:

<form role='search'>
<input id="searchBar" type="text" placeholder="Search Term" aria-label="Search Term">
<button>Search</button>
</form>

Using an aria-label gets the job done

Still the best way is to label your inputs, and link the label to the input id with “for”. It’s simple, and maybe boring, but it works, for everyone.

<form role='search'>
<label for="searchBar" >Search Term</label>
<input id="searchBar" type="text">
<button>Search</button>
</form>

It’s important to note, labels help to set keyboard focus to form control inputs, allowing sighted users the ability to click on the label as well as the input itself. Plus they have universal browser and screen reader support.

Of course there are many ways to do this, and much better documentation, listed below, but these core concepts will give your search bars and search forms the basics needed for accessibility.

This blog is the first in a series on accessibility, striving to provide a starting point for building common components with accessibility in mind.

Additional Resources

--

--

JD Brewer-Hofmann

Full-time Software Engineering Student at Flatiron School, musician, and lover of plants