如何将输入元素放在与其标签相同的行上? [英] How can I put an input element on the same line as its label?
问题描述
我想在同一行放置标签
和输入[type = text]
我想要输入
的宽度填充包含元素的剩余宽度,而不考虑标签的文本长度(见第一个图像)。
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).
我试图使用 width:auto;
为输入
它似乎有一个静态宽度。我也尝试了 width:100%;
,但是将输入
移到新行(见第二个图像)。
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).
如何使用CSS实现这个目的?
How can I achieve this using CSS?
推荐答案
这可能没有JavaScript,请参阅: http://jsfiddle.net/Khmhk/
It's possible without JavaScript, see: http://jsfiddle.net/Khmhk/
这适用于IE7 +和所有现代浏览器。
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%
}
在这个例子中 overflow:hidden
的原因很奇怪,因为在此处解释。
The reason why overflow: hidden
is so magically useful in this instance is explained here.
display:table-cell
是另一个选项,请参阅: http://jsfiddle.net/Khmhk/1/
display: table-cell
is another option, see: http://jsfiddle.net/Khmhk/1/
此适用于IE8 + 和所有现代浏览器:
HTML:
$ b
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%
}
这篇关于如何将输入元素放在与其标签相同的行上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!