Skip to main content

How to add a clear button to an input with CSS

ยท 2 min read

When creating a form, it is inevitable to add a clear button to facilitate the user to clear the form, which is a very good user experience.

Maybe your ideas will be implemented using pseudo-elements? do you know HTML5's new input element type=search attribute can be used to add a clear button? ๐Ÿ‘

<input class="input" type="search" placeholder="keyword" />

The following example

Generally, a native icon is not what you want, but we can beautify the icon. In chrome, for example.


[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: none;
width: 36px;
height: 36px;
border: 0;
background: url("data:image/svg+xml,%3Csvg xmlns='' viewBox='0 0 512 512'%3E %3Cpath d='M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z'%3E%3C/path%3E %3C/svg%3E")
center no-repeat;
background-size: 16px;
cursor: pointer;
opacity: 0.4;
transition: 0.2s;

Unfortunately, it only works in the webkit kernel, IE can use ::ms-clear. We can only add a button to it manually.


Sadly, we have to do it the old way.

<div class="form-group">
<input class="input" type="search" placeholder="keyword">
<button class="clear">X</button>

And then we can combined with the :placeholder-shown selector.

.clear {
position: absolute;
right: 0;
top: 0;
display: none;

input:not(:placeholder-shown) + button{
display: block;

It's amazing! Right! ๐Ÿ˜ƒ you can add what ever you want to style the clear button.