CSS拉伸文本框以填充剩余空间

时间:2016-06-17 14:21:30

标签: html css

我有一个带标签和文本框的div,我只想让文本框伸展以填充页面上的剩余空间。我知道100%宽度不包括任何填充或边距值,所以我已经添加到textbox和div。我搜索了许多类似的主题,但我的文本框总是下降到标签下方的新行。我错过了什么?我将我的CSS内联仅用于测试目的。

<div style="padding-right:10px;">
    <asp:Label ID="Label1" runat="server" Text="Label" style="float:left; width:150px; display:inline-block"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server" style="display:inline-block; width:100%; padding-right:0"></asp:TextBox>
</div>

1 个答案:

答案 0 :(得分:4)

您可以使用calc() + box-sizing: border-box;作为已知宽度标签。

&#13;
&#13;
.container label,
.container input[type="text"] {
  float: left;
}
.container label {
  width: 150px;
}
.container input[type="text"] {
  width: calc(100% - 150px);
  box-sizing: border-box;
}
&#13;
<div class="container">
  <label>Label Example</label>
  <input type="text">
</div>
&#13;
&#13;
&#13;

或者,使用flexbox,这使得它非常容易适用于动态宽度。

&#13;
&#13;
.container {
  display: flex;
  align-items: flex-start;
}
.container input[type="text"] {
  flex: 1; /*take all the available space*/
}
&#13;
<div class="container">
  <label>Label Example</label>
  <input type="text">
</div>
&#13;
&#13;
&#13;

如果您需要支持旧版浏览器,请尝试使用CSS表。注意,为了使其工作,我在输入框周围添加了一个span标记。

&#13;
&#13;
.container {
  display: table;
  width: 100%;
}
.container label,
.container span {
  display: table-cell;
}
.container label {
  white-space: nowrap;
}
.container span {
  width: 100%;
}
.container input[type="text"] {
  width: 100%;
  box-sizing: border-box;
}
&#13;
<div class="container">
  <label>Label Example</label>
  <span><input type="text"></span>
</div>
&#13;
&#13;
&#13;

相关问题