Home > Software design >  How to get the clear 'X' button inside the input field?
How to get the clear 'X' button inside the input field?

Time:02-16

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 >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;
}

CodePudding user response:

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 >
  <input id="myInput" type="text" placeholder="Search Text...">
  <button >X</button>
</div>

CodePudding user response:

<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.

  • Related