3

I'm tempting to resort to tables here since I cannot seem to come up with some CSS that will accomplish what I'm trying to create here.

I have a <div> container that contains two things:

  • a text entry box (<input type='text' />)
  • a button (<input type='button' />)

I want the button right-aligned (I haven't given it a fixed width, but I easily could). The text entry box should be directly left of the button and take up the remaining space. Here is an example of what I'm looking for:

enter image description here

Unfortunately, the following HTML isn't accomplishing this (pardon the inline styles - for demonstration purposes only):

<input type="button" value="Test" style="float: right;" />
<input type="text" style="display: block; width: 100%;" />

I tried adding a <div> wrapper, but that didn't work either. What am I doing wrong? I could accomplish this easily with a <table> layout, but I'm sure I must be missing something and that there is a better way of doing it.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

2 Answers2

10

It's possible without <table>, but it's not very obvious.

See: http://jsfiddle.net/thirtydot/wE7jc/2/

<input type="button" value="Test" style="float: right;" />
<div style="overflow: hidden; padding-right: 8px">
    <input type="text" style="width: 100%;" />
</div>

The reason this works is explained here.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • What's so magical about `'overflow: hidden'`? What does it do and why is it necessary? – Nathan Osman Oct 09 '11 at 04:58
  • Did you see the (second) link in my answer? I added it a couple of minutes after the initial answer, and it explains nicely why this works. – thirtydot Oct 09 '11 at 05:02
  • If you need the input box to have padding, you will have to add `-[vender]-box-sizing:border-box` or else the input box will be clipped by the `overflow:hidden`. – Pwner Nov 21 '12 at 18:24
2

As long as you don't mind a fixed width button, this should do:

http://jsfiddle.net/4WghJ/

Basically just wrapped the input in a div with a right margin to compensate for the button.

James Montagne
  • 77,516
  • 14
  • 110
  • 130