CSS让输入消耗可用的宽度

时间:2012-09-07 15:29:14

标签: css text input

我有以下标记作为基础:

<div>
    <span>some dynamic text</span>
    <input type="text" />
</div>

我希望输入显示在带有文本的行中(总是一行,但长度不同),并根据文本长度消耗可用的宽度。如果需要,可以更改标记。两个元素都应该是父元素宽度的100%。

1 个答案:

答案 0 :(得分:2)

我能想到的两种方法:

第一个:

您可以使用CSS模拟表的行为;

HTML:

<div class = "container">
    <div class = "text">Glee is awesome!</div>
    <div class = "inputtext"><input type="text" /></div>
</div>

CSS:

.container {
    display: table;
    width: 100%; /*how much should both the text and the input take*/
}
.container .text {
    white-space: nowrap;
    display: table-cell;
    width: 1px; /*make sure it's only as wide as needed*/
}
.container .inputtext {
    display: table-cell;
}
.container input {
    width: 100%; /*let the input take all available space*/
}

小演示:little link

第二个:

此方法依赖于浮动:

HTML:

<div class = "text">Glee is awesome!</div>
<div class = "inputtext"><input type = "text" /></div>

CSS:

.text {
    float: left;
}
.inputtext {
    overflow: hidden; /*this is the key here*/
}
input {
    width: 100%;
}

另一个小演示:little link