How to make a search field
Short answer
Make a form with a type="search" field and a button, and wrap the form in <search>:
<search>
<form>
<input type="search" name="q" placeholder="Search the site" aria-label="Search">
<button>Find</button>
</form>
</search>The search type adds a cross to clear the field, and on a phone the Enter key turns into "Search". The <search> element marks the search area for screen readers. For older browsers the form gets role="search" instead, as in the next example.
The field and the button together
Flexbox joins the field and the button into one rounded block:
<style>
.search { display: flex; max-width: 320px; border: 1px solid silver; border-radius: 999px; overflow: hidden; }
.search input { flex: 1; min-width: 0; padding: 8px 14px; border: 0; font: inherit; outline: none; }
.search button { padding: 0 16px; border: 0; background: steelblue; color: white; cursor: pointer; }
.search:focus-within { outline: 2px solid lightblue; }
</style>
<form class="search" role="search">
<input type="search" name="q" placeholder="Search" aria-label="Search">
<button>Find</button>
</form>:focus-within highlights the whole form when the focus is in the field — since the field itself lost its outline.
A magnifier icon inside the field
The icon is placed over the field with absolute positioning, and padding on the left leaves room for it:
<style>
.field { position: relative; display: inline-block; }
.field svg { position: absolute; left: 10px; top: 50%; translate: 0 -50%; pointer-events: none; }
.field input { padding: 8px 8px 8px 34px; border: 1px solid silver; border-radius: 8px; }
</style>
<label class="field">
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="5" fill="none" stroke="gray" stroke-width="2"/><path d="M11 11l4 4" stroke="gray" stroke-width="2"/></svg>
<input type="search" placeholder="Search" aria-label="Search">
</label>pointer-events: none lets a click on the icon pass through to the field.
Common mistake
The search field is left without a label — "it is obviously a search anyway". A screen reader announces just "edit text". If there is no visible label, add aria-label="Search", as in the examples.
Functions used in this recipe
- <search> — An area for searching or filtering on the page.
- <input> — An input field; its kind is set by the `type` attribute.
- <form> — A form: collects data from its fields and sends it to the server.
- type — The kind of an `<input>` field: from text and numbers to a date, colour and file.
- aria-* — Accessibility attributes: the role, name and state of an element for screen readers.