tags:

views:

1676

answers:

3

Let's say I have an html snippet like this:

<div style="width:300px;">
    <label for="MyInput">label text</label>
    <input type="text" id="MyInput" />
</div>

This isn't my exact code, but the important thing is there's a label and a text input on the same line in a fixed-width container. How can I style the input to fill the remaining width of the container without wrapping and without knowing the size of the label?

A: 

The short answer is you can't without using JavaScript, the label and input would have to have a fixed width also. But then if you have a number of inputs on a form, having them line up makes sense from a usability point of view anyway, so it's not such a bad idea.

roryf
A: 

You can't really do it on CSS level, you'd have to use a bit of Javascript-trickery to achieve this goal, meaning you'd have to sniff the width of the parent element, deduct the width of the label and set the width to the resulting amount of pixels.

But with pure html+css, no can do.

Tommi Forsström
+3  A: 

as much as everyone hates tables for layout, they do help with stuff like this, either using explicit table tags or using display:table-cell

<div style="width:300px; display:table">
    <label for="MyInput" style="display:table-cell; width:1px">label&nbsp;text</label>
    <input type="text" id="MyInput" style="display:table-cell; width:100%" />
</div>

(there should be a &nbsp; instead of a space between label and text, but I can't figure out how to format it so SO won't convert it to a space)

cobbal
Would this work with IE6? Otherwise I may have to actually define a little table for this :(
Joel Coehoorn
not sure, I would say do a quick test to see what they do, but I don't have easy access to IE
cobbal
display:table only works in IE8
Jimmie R. Houts
That's okay: this pointed me towards something that does work.
Joel Coehoorn
Care to share Joel?
John