How do I put a clear button inside my HTML text input box like the iPhone does?

Nowadays with the <input type="search"> element, it’s pretty simple:

<input type="search" placeholder="Search..."/>

Supported browsers will automatically render a usable clear button in the field by default.

plain HTML5 search input field

The clear button is a ::-webkit-search-cancel-button CSS pseudo-element automatically inserted by Webkit/Blink-based browsers (though it’s technically still a non-standard feature).


If you use Bootstrap, you’ll have to add a CSS override to force the pseudo-element to show:

input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

bootstrap search input field


Officially, the -webkit-search-cancel-button psuedo-element is non-standard and should not be relied upon as a built-in HTML feature across browsers.

Notably Firefox does not render the clear button by default as of version 110, but they have plans to enable it eventually: https://bugzilla.mozilla.org/show_bug.cgi?id=1654288. You can check up-to-date browser compatibility information on MDN or CanIUse.com.

The most reliable, future-proof, cross-browser approach is to use a form with an explicit <input type="reset"/> element nearby to allow clearing the Search form with a button. This also makes it easier to add accecibility hints and style the clear button directly with CSS.

<form action="/search">
  <input type="search" placeholder="Search..."/>
  <input type="reset" value="X" alt="Clear the search form">
  <input type="submit" value="Search">
</form>

Search with manual input reset button appended


Extras: Safari/WebKit browsers can also provide extra features when using type="search", like results=5, enterkeyhint="...", and autosave="...", but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:

input[type=search] {
    -webkit-appearance: none;
}

See the MDN Documentation, CanIUse.com, or CSS-Tricks.com for more complete and up-to-date info about the features provided by <input type="search"/> in browsers today.

Leave a Comment