我正在尝试在不使用表格的情况下在html中创建一个灵活的行,以便该行的一个元素可以获取额外的水平空间。我这里有一个基本的解决方案,但看起来很尴尬。例如,按钮必须位于div中的输入之前,以便所有内容都在同一行上,即使在页面上它看起来像是在它之后。此外,添加第二个按钮时,事情变得更加麻烦(我的示例中未包含)。有谁知道更好的方法来解决这个问题?这是一个JSFiddle,我已粘贴下面的代码。有效的解决方案需要足够灵活,以便可以轻松地将更多固定宽度的元素添加到行中。请注意,在示例中,灰色框可以重新调整大小,文本输入将自动扩展。 http://jsfiddle.net/jjfPK/8/
<div id="grayBox">
<div id="searchbar">
<button>Search</button>
<input type="text"></input>
</div>
</div>
<style = "text/css">
#grayBox
{
width:400px;
background-color:lightgray;
}
#searchbar
{
margin-right:70px;
padding: 10px;
}
#searchbar input
{
width:100%;
}
#searchbar button
{
float:right;
margin-right:-70px;
}
</style>
答案 0 :(得分:1)
尝试使用display: table
。当你有一个需要像表一样表现的非表格数据的布局时,你应该使用它。 IE7不支持,但IE8 +和所有其他主流浏览器都支持。
需要修改html以包含虚拟单元格的容器。
<div id="grayBox">
<div id="searchbar">
<div><input type="text" /></div>
<div><button>Search</button></div>
<div><button>Search</button></div>
<div><button>Search</button></div>
</div>
</div>
CSS应用表格,行和单元格样式。使用>
定位直接后代。然后使用first-of-type
使第一个单元格尽可能大。
#grayBox
{
display:table;
width:400px;
height:400px;
background-color:lightgray;
}
#searchbar
{
display:table-row;
margin-right:100px;
padding: 10px;
}
#searchbar > div {
display:table-cell;
}
#searchbar > div:first-of-type {
width: 100%; padding: 0px 5px 0px 5px;
}
答案 1 :(得分:0)
请参阅演示小提琴:您可以根据需要更改值。
演示:http://jsfiddle.net/jjfPK/10/embedded/result/
更新小提琴: 3月25日
小提琴:http://jsfiddle.net/aEyqC/1/
演示:http://jsfiddle.net/aEyqC/1/embedded/result/
HTML:
<div id="grayBox">
<ul id="searchbar">
<li><input type="text"></input></li>
<li><button>Search</button></li>
</ul>
</div>
CSS:
#grayBox
{
width:400px;
height:400px;
background-color:lightgray;
}
#searchbar
{
padding: 10px;
overflow:hidden;
}
#searchbar li
{
display:inline;
}
#searchbar input
{
width:80%;
}
#searchbar button
{
float: right;
width: 16%;
}