我有以下片段:
<html>
<body>
<div style="width: 700px;">
<span>test</span>
<input style="width: 100%;"></input>
</div>
</body>
</html>
但这并不是我想要的。我希望跨度和输入一起占div的100%,即输入从跨度结束的地方开始,一直填充到div的宽度,而不中断到下一行。我该怎么做?
如果您需要适当的流体宽度:
请参阅:http://jsfiddle.net/kxEML/
CSS:
.inputContainer {
width: 300px;
border: 1px dashed #f0f
}
.inputContainer label {
float: left;
margin-right: 5px;
background: #ccc
}
.inputContainer div {
overflow: hidden;
}
.inputContainer input {
width: 100%;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
display: block
}
HTML:
<div class="inputContainer">
<label>test</label>
<div><input /></div>
</div>
当然它不起作用。您的输入占用了所有的700px。
<div style="width: 700px;">
<span style="width:20%">test</span>
<input style="width: 80%;"></input>
</div>
这应该会更好。
只需设置它们,使它们的宽度总计约为100%,并且float
它们相邻。在您的代码段中,input
占据了div的100%,因此跨度必须在其上方。为了使它们能够在同一行上切换,它们的总长度必须小于100%或700px才能放入div。设置float
属性会告诉浏览器使它们尽可能向左齐平,因为它们可以容纳,所以它们最终会在同一线上并排。:D
<html>
<body>
<div style="width: 700px;">
<span style="width: 49%; float: left; background-color: blue;">test</span>
<input style="width: 49%; float: left; background-color: green;"></input>
</div>
</body>
</html>
对input
使用width:100%
将使其成为700px
。添加所需的文本宽度,使行最大,因此input
将转到下一行。因此,您可以将input
的width
更改为95%
以适应该行。
演示:http://jsfiddle.net/q75C8/
使用jQuery的另一种解决方案可能如下:
$("input").width(($("div").width()-10)-$("span").width());
演示:http://jsfiddle.net/q75C8/2/
第页。S删除</input>
,不是必需的。
试试这样的东西:
<html>
<head>
<style type="text/css">
div { width: 700px; }
label { display: block; text-align: right; }
label > input { width: 50%; }
</style>
</head>
<body>
<div>
<label for="user-name">User Name: <input name="user" id="user-name" /></label>
</div>
</body>
</html>
使用LABEL而不是SPAN可以使盲人顺利工作。
在LABEL上设置"display:block"使其扩展到容器(DIV)宽度的100%,并单独在一行上开始。
在INPUT上设置"宽度:50%"会使其占据LABEL宽度的一半。
"text-align:right"使标签的文本与INPUT的开头齐平。
编辑:哦,注意LABEL的FOR属性指的是INPUT的ID,而不是它的NAME。编辑示例以澄清这一点。
<html>
<style type="text/css">
.left {
float:left;
width:15%;
margin:0px auto;
padding:0px;
}
.right {
float:right;
width:85%;
margin:0px auto;
padding:0px;
}
.clearthis {
width:100%;
margin:0px auto;
padding:0px;
clear:both;
}
</style>
<body>
<div style="width: 700px;">
<div class="left">
<span>test</span>
</div>
<div class="right">
<input style="width: 100%;"></input>
</div>
<div class="clearthis"></div>
</div>
</body>
</html>
像这样的东西应该可以在上运行
我是用表得到的:
<html>
<body>
<div style="width: 700px;">
<table border="0" style="width: 100%;">
<tr>
<td><span>test</span></td>
<td style="width: 100%;"><input style="width: 100%;"></input></td>
</tr>
</table>
</div>
</body>
</html>
div和CSS的替代方案是使用以下表格:
<table>
<tr>
<td><span>Username</span></td>
<td><input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</td>
</tr>
<tr>
<td><span>Password</span></td>
<td><input id="password" name="password" value="" type="password" placeholder="Password">
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">Login</button>
</td>
</tr>
</table>