Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put an input element on the same line as its label?

Tags:

html

css

I would like to put a label and an input[type=text] on the same line, and I would like for the input's width to fill the remaining width of the containing element, regardless of the length of the label's text (see first image).

I tried to use width: auto; for the input, but it seems to have a static width. I also tried width: 100%;, but that moves the input to a new line (see second image).

http://i.stack.imgur.com/G8rKG.jpg

How can I achieve this using CSS?

like image 692
enenkey Avatar asked Aug 04 '11 09:08

enenkey


People also ask

How do I keep HTML elements on the same line?

To get all elements to appear on one line the easiest way is to: Set white-space property to nowrap on a parent element; Have display: inline-block set on all child elements.

How do you bind a label to an input element?

<input type="tel"> <input type="text">


1 Answers

It's possible without JavaScript, see: http://jsfiddle.net/Khmhk/

This works in IE7+ and all modern browsers.

HTML:

<label for="test">Label</label> <span><input name="test" id="test" type="text" /></span> 

CSS:

label {     float: left } span {     display: block;     overflow: hidden;     padding: 0 4px 0 6px } input {     width: 100% } 

The reason why overflow: hidden is so magically useful in this instance is explained here.


display: table-cell is another option, see: http://jsfiddle.net/Khmhk/1/

This works in IE8+ and all modern browsers:

HTML:

<div class="container">     <label for="test">Label</label>     <span><input name="test" id="test" type="text" /></span> </div> 

CSS:

.container {     display: table;     width: 100% } label {     display: table-cell;     width: 1px;     white-space: nowrap } span {     display: table-cell;     padding: 0 0 0 5px } input {     width: 100% } 
like image 143
thirtydot Avatar answered Oct 20 '22 21:10

thirtydot