众所周知,在没有设置任何样式情况下,浏览器默认同级的div宽度是充满整行的,即默认宽度最大化。正常情况下,为了使得这两个div并排,会使用float:left;然后发现二者确实并排了,但第二个div并没有充满剩余部分,因为有了浮动元素,默认宽度最小化。
在此,提供两种css的解决方案,其中一种是css3的解决方案。
以下是例子html代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
border: solid #000000 1px;
}
</style>
</head>
<body>
<div id = "first">first</div>
<div id = "second">second</div>
</body>
</html>
一种是给first设置宽度,且使用绝对定位。然后second的margin-left值为first宽度。使用绝对定位是因为绝对定位的元素并不占有文档空间,此时second的margin-left其实是相当于整个窗口来说。此方法还可以推广到三栏并列的情况。思想是左右栏使用绝对定位,并设置一定宽度,left和right分别为0,中间一栏的margin-left和margin-right分别为左右栏的宽度。
/*添加css代码*/
#first{
background-color: yellow;
position: absolute;
left: 0;
width: 50px;
}
#second{
margin-left: 50px;
}
另一种使用css3的一个新特性,但该方法在我给的例子中,必须更改下html代码,且该方法在IE下无效,因为IE不支持css3的box-oriented和box-flex属性。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
border: solid #000000 1px;
display: box;
display: -webkit-box;
display: -moz-box;
-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
box-orient: horizontal
}
#first{
background-color: yellow;
}
#second{
background-color: green;
}
.flex{
-webkit-box-flex: 1;/*在有多个box-flex属性时,其数值表示比例,此时只有一个box-flex属性,所以1代表充满*/
-moz-box-flex:1;
}
</style>
</head>
<body>
<div>
<div id = "first">first</div>
<div id = "second" class = "flex">second</div>
</div>
</body>
</html>