Search code examples
htmlcssvertical-alignment

How do I make a button and an input stay on the same line inside a table cell?


Given:

<table>
<tr>
    <td>
        <div id="dv">
            <button id="bt" type="button">X</button>
            <input id="num" type="number" value="1"/>
        </div>
    </td>
    <td>
        <input type="text" value="aaa"/>
    </td>
</tr>
</table>​

http://jsfiddle.net/mark69_fnd/ZZFc5/1/

enter image description here

But, if I resize the window, then I get this:

enter image description here

What I want to achieve is that:

  1. All the controls stay on the same line, even when the window is resized.
  2. The input controls occupy all the available space (the button size can be made constant).
  3. When the window is resized, the input controls are resized as well.
  4. The X button must share the first cell with the input control.
  5. No absolute sizes should be used, except for the X button.

This should be simple, but I just cannot get my head around it.

Please, share your wisdom.

EDIT

If possible, I would like to avoid specifying absolute values (like pixels) for all, but the X button, which may be given absolute width and height.

EDIT2

Added the 5th constraint.


Solution

  • If you can stick a width on the table like 100%, then you can try something like the following.

    I modified your HTML to add an id to the text field; nothing more.

    HTML:

    <table>
        <tr>
            <td>
                <div id="dv">
                    <button id="bt" type="button">X</button>
                    <input id="num" type="number" value="1"/>
                </div>
            </td>
            <td>
                <input id="txt" type="text" value="aaa"/>
            </td>
        </tr>
    </table>​​​​
    

    CSS:

    table {
        width: 100%;
    }
    tr td {
        position: relative;
        width: 50%;
    }
    
    #bt {
        width: 25px;
        top: 0;
        left: 0;
        position: absolute;
    }
    
    button {
        padding: 0;
        margin: 0;
    }
    
    #num {
        position: absolute;
        top: 0;
        left: 25px;
        right: 0;
    }
    
    #txt {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
    }
    

    See the JSFiddle I forked from yours.

    Basically I set the size of the button to 25px, and then set the widths of each of the <td>s to 50% of the table width. Then I used absolute positioning to tell the textfield and input field to take up all of the available horizontal room and nothing else. The components will therefore resize when you resize the window, but will never "drop" onto a second row. ​