Udo Udo - 5 months ago 29
CSS Question

search box with button in textbox

i want to create a textbox that have a button inside of it just like i see in some sites, usually there is a textbox and at the right hand corner a button with a hand lens image and when the button is clicked the form is submitted. I have tried using divs to create something similar but i dont seem to get it. How is it done with css or are there some jquery magic to it ?

Answer

Using a wrapper

The technique you're referring to doesn't actually have the button inside the textbox normally, the border and background of the button and textbox simply blend in with a wrapper div. Here is a basic example:

jsFiddle

enter image description here

HTML

<div class="wrapper">
    <input type="text" />
    <button>GO</button>
</div>

CSS

.wrapper {
    border:1px solid #000;
    display:inline-block;
}

input,
button {
    background-color:transparent;
    border:0;
}

Using position:absolute

An alternative method is to position the button absolutely and attach it to the right. A benefit of this is that you can more easily implement the focus/active border around the text box. You can get around the text under the button issue by giving padding-right to the text box.

jsFiddle

enter image description here

.wrapper {
    border:1px solid #000;
    display:inline-block;
    position:relative;
}

input,
button {
    background-color:transparent;
    border:0;
}

button {
    position:absolute;
    right:0;
    top:0;
}

input {
    padding-right:30px; /* button padding */
}