这其实是遇到的一道面试题:面试官要求实现左侧固定宽度,右侧宽度自适应的两列布局。用尽可能多的方法来实现。
这是很简单的一个题目,我只是想到了浮动和定位两种方式,但是其中还有回答错误的地方,比如绝对定位的div,我说不用管宽度,是自己拉升的,可是回来后一查资料,发现我说错了,绝对定位的div是宽度随着内容撑开的,并不是自动去拉升的。
仔细分析其原因:是因为平时写页面的时候,仅仅局限于实现功能了之后,就没有去深入的思考。
下面,我将总共用四种方法去实现:
首先,HTML文档结构为:
<body>
<div class="outer">
<div class="left">固定宽度</div>
<div class="right">自适应宽度</div>
</div>
</body>
在外层div(类名为outer)的div中,有两个子div,类名分别为left和right,其中left为固定宽度,而right为自适应宽度。
以下为css样式:
- 方法1:左侧div设置成浮动:float: left,右侧div宽度会自拉升适应
.outer {
width: 100%;
height: 500px;
background-color: yellow;
}
.left {
width: 200px;
height: 200px;
background-color: red;
float: left;
}
.right {
height: 200px;
background-color: blue;
margin-left: 200px;
}
- 方法2:对右侧:div进行绝对定位,然后再设置right=0,即可以实现宽度自适应。这是因为:绝对定位元素的第一个高级特性就是其具有自动伸缩的功能,当我们将 width 设置为 auto 的时候(或者不设置,默认为 auto ),绝对定位元素会根据其 left 和 right 自动伸缩其大小。
参考文献:CSS position: absolute 绝对定位精讲
http://blog.csdn.net/devilpace/article/details/51912382
.outer {
width: 100%;
height: 500px;
background-color: yellow;
position: relative;
}
.left {
width: 200px;
height: 200px;
background-color: red;
}
.right {
height: 200px;
background-color: blue;
position: absolute;
left: 200px;
top:0;
right: 0;
}
- 方法3:将左侧div进行绝对定位,然后右侧div设置margin-left: 200px;
.outer {
width: 100%;
height: 500px;
background-color: yellow;
position: relative;
}
.left {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
}
.right {
height: 200px;
background-color: blue;
margin-left: 200px;
}
- 方法4:使用flex布局
.outer {
width: 100%;
height: 500px;
background-color: yellow;
display: flex;
flex-direction: row;
}
.left {
width: 200px;
height: 200px;
background-color: red;
}
.right {
height: 200px;
background-color: blue;
flex: 1;
}