'How to get the clear 'X' button inside the input field?

I created a search field where the user can type some text. Next to the search field, is an 'X' button which is there to clear of search inputs. The problem I notice is that, on my phone, the 'X' button is just outside of the input search box: Here is the example. How can I get the 'X' to be inside the search box?

HTML:

<input id="myInput" type="text" placeholder="Search Text...">
<button class="clear">X</button>

CSS:

#myInput{
    width: 40%;
    height: 33px;
    border: 1px solid #000;
    font-family: 'arial';
    font-size: 19px;
}
.clear {
    position: relative;
    z-index: 1;
    margin-left: -29px;
    background: transparent;
    border: 0px none;
    font-size: 19px;
    font-weight: bold;
    vertical-align: middle;
}


Solution 1:[1]

The easiest way to solve this is to wrap the input and button in an element with position: relative + width: min-content. Then you only need to apply position: absolute + right: value to the button

.wrapper {
  position: relative;
  width: min-content;
}

.clear {
  position: absolute;
  right: 0px;
}
<div class="wrapper">
  <input id="myInput" type="text" placeholder="Search Text...">
  <button class="clear">X</button>
</div>

Solution 2:[2]

<input type="search" />

Works in Chromium-based browsers at least. It does have some undocumented side effects though, like ESC will clear the input.


If you're intent on using your own custom clear button, adapt this idea by putting both elements into a shared parent element. Have the input take up the entire size of the parent element, and then use position: absolute; on the Clear button.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tacoshy
Solution 2 Slbox