TAGS :Viewed: 8 - Published at: a few seconds ago

[ How to stretch input field to full width? ]

I have a simple HTML form. I'd like the right widgets in the second column (text field, combox, and so on) to stretch and fill the full column.

My HTML looks like this:

<table class="formTable">
  <tr>
    <td class="col1">Report Number</td>
    <td class="col2"><input type="text"/></td>
  </tr>
  <tr>
    <td class="col1">Report Type</td>
    <td class="col2"><select></select></td>
  </tr>
</table>

My CSS looks like this:

.formTable {
  border-color: black;
}

.formTable td {
  padding: 10px;
}

.formTable .col1 {
  text-align: right;
}

.formTable .col2 {
  width: 100%;
}

Any ideas?

Answer 1


You can specify that all of the children of class "col2" have a width of 100% by adding the following:

.col2 * { width:100%;}

See my dabblet example: http://dabblet.com/gist/2227353

Answer 2


Start with semantic markup since this isn't tabular data. Also, with added labels, we don't need extra wrapper DIVs, which is cleaner.

<ul class="formList">
    <li>
        <label for="input_1">
            Report Number
        </label>
        <input id="input_1" name="input_1" type="text" />
    </li>
    <li>
        <label for="input_2">
            Report Type
        </label>
        <select id="input_2" name="input_2"></select>
    </li>
</ul>

Then add the CSS:

.formList {
    border:1px solid #000;
    padding:10px;
    margin:10px;
}
label {
    width:200px;
    margin-left:-200px;
    float:left;
}
input, select {
    width:100%;
}
li {
    padding-left:200px;
}

JS Fiddle Example: http://jsfiddle.net/6EyGK/

Answer 3


You can use:

.col2 * {
    width: 100%;
}

To match any .col2 descendant. as you can see here. Or:

.col2 > * {
    width: 100%;
}

To match just the immediate children.

Answer 4


Other semantic markup additionaly to Matthew Darnells answer:

If you wrap the labels around the inputs and selects, you can avoid using the forand id attributes.

<ul class="formList">
    <li>
        <label>
            Report Number
        <input name="input_1" type="text" />
        </label>
    </li>
    <li>
        <label>
            Report Type
        <select name="input_2"></select>
        </label>
    </li>
</ul>

Or use a definition list which might give you additional control

<dl class="formList">
    <dt>
        <label for="input_1">
            Report Number
        </label>
    </dt>
    <dd>
        <input id="input_1" name="input_1" type="text" />
    </dd>
    <dt>
        <label for="input_2">
            Report Type
        </label>
    </dt>
    <dd>
        <select id="input_2" name="input_2"></select>
    </dt>
</dl>