CSS variable width element to fill in space
In a form, I would like the input:text to fill the remain space after the label to the form is left and right justified.
The label have number of characters so I can't set a fixed width on the label.
Code exa开发者_如何学Pythonmple:
<fieldset>
<legend>User Info</legend>
<p><label>First Name :</label><input type="text"...></p>
<p><label>Last Name : </label><input type="text"...></p>
<p><label>Completed Email Address :</label><input type="text"...></p>
</fieldset>
How can I style the input to fill the remaining space after the text.
Thanks.
<!doctype html>
<html>
<head>
<style>
.grid { width: 100%; display: table; table-layout: auto; }
.row { display: table-row; }
label.cell { white-space: nowrap; display: table-cell; }
span.cell { width: 100%; display: table-cell; }
span.cell input { width: 100%; display: block; }
</style>
</head>
<body>
<fieldset>
<legend>User Info</legend>
<div class="grid">
<div class="row"><label class="cell">First Name:</label> <span class="cell"><input type="text" /></span></div>
</div>
<div class="grid">
<div class="row"><label class="cell">Last Name:</label> <span class="cell"><input type="text" /></span></div>
</div>
<div class="grid">
<div class="row"><label class="cell">Completed Email Address:</label> <span class="cell"><input type="text" /></span></div>
</div>
</fieldset>
</body>
</html>
Won't work in older browsers.
LE: if you don't need/want/have to support old browsers such as IE 6 and 7, use this code. Otherwise, use JavaScript. Ooor use this code an throw in some JavaScript for IE 6 and 7. Yeah, I think that's the best way to do it :D
I posted this in a comment first, but was advised to post as an answer instead. This is not a CSS solution, but a table-based one. However, it should work on all browsers (though I didn't test this). span
inside label's td
is needed to workaround IE's bug of not applying white-space: nowrap
to table cells.
<table width="100%">
<tr>
<td width="1"><span style="white-space: nowrap;">First name:</span></td>
<td><input style="width:100%"/></td>
</tr>
</table>
<table width="100%">
<tr>
<td width="1"><span style="white-space: nowrap;">Last name:</span></td>
<td><input style="width:100%"/></td>
</tr>
</table>
<table width="100%">
<tr>
<td width="1"><span style="white-space: nowrap;">Completed Email Address:</span></td>
<td><input style="width:100%"/></td>
</tr>
</table>
You can try using floats for the left (or right) side, and "block formatting context"ifying the right side items.
Read about block formatting contexts in css at the YUIblog
Fiddle: http://jsfiddle.net/uS3Cv/1/
精彩评论