有一个<div id="MyDiv">
元素,根据页面宽度调整大小。它包含<input>
和<a>
元素。
我如何让<a>
在<div>
和<input>
的右侧对齐,以适应<div>
的左侧和<a>
的右侧之间的自由空间?
此外,<a>
不应该跳到下一行,并且容器上也定义了min-width
和max-width
。这是代码:
<div id="MyDiv" style="background:#AAAAAA; width:100%; min-width:300px; max-width:600px;">
<input type="text" id="MyInput"/>
<a id="MyButton" href="#">Button</a>
</div>
和demo。
这可以通过CSS3轻松完成,尽管它不适用于IE9或更低版本。 IE10是第一个支持该标准的Internet Explorer版本。其他浏览器already support相关的Flexible Box属性。
div {
background: #AAAAAA;
width: 100%;
min-width: 300px;
max-width: 600px;
display: -webkit-flex;
}
input {
-webkit-flex: 1;
}
a {
margin: 0 10px;
}
<div>
<input type="text" />
<a href="#">Button</a>
</div>
最好的选择是使用jQuery来计算宽度。试试这个:
$( window ).bind("resize", function(){
fitInput();
});
//resize on window change
$(document).ready(function(){
fitInput();
});
//resize after loading
function fitInput(){
var divW = $("#MyDiv").width();
var buttonW = $("#MyButton").width();
$("#MyInput").width(divW - buttonW - 10);
}
//resize function
你可以使用绝对定位:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="MyDiv" style="position:relative;background:#AAAAAA; min-width:300px; max-width:600px;padding:0px 2px">
<input type="text" id="MyInput" style="padding:0px;margin:0px;border:0px;width:100%;"/>
<a id="MyButton" href="#" style="position:absolute;right:0px;top:0;padding:0px 2px; background:#aaa;">Button</a>
</div>
<body>
</html>
试试这个HTML:
<div id="MyDiv" style="background:#AAAAAA; width:100%; min-width:300px; max-width:600px;">
<input type="text" id="MyInput" style="width:74%;float:left"/>
<a id="MyButton" href="#" style="width:24%;float:right">Button</a>
</div>
只需在<head>
标签中添加此项
input{width:92%;}