注:(本文所有例子以左侧固定,右侧自适应举例)
html结构为
<div class="f">
<div class="left">left</div>
<div class="right">right</div>
</div>
一、两栏布局
首先我们需要知道什么是两栏布局:一侧的宽度固定,另一侧自适应
1.让左侧盒子浮动,设置右侧盒子宽度为100%
.left {
float: left;
width: 200px;
height: 200px;
background-color: red;
}
.right {
width: 100%;
height: 200px;
background-color: green;
}
但是用这种方式的时候我们要注意,并不是绿色盒子的宽度只有右侧,而是右侧盒子的宽度还是整个浏览器的宽度,但是给我们呈现出来的是只有右侧,并且我们在右侧嵌套一些标签或者只写写入文字,都是会在右侧位置显示,并不会在开始的地方显示。
2.定位方法:给父级盒子添加position:relative,固定一侧的盒子position:absolute,另一侧宽度100%,但是要给右侧盒子添加margin-left:左侧盒子宽度,不然就会右侧盒子的宽度为整个浏览器的宽度
.f{
position: relative;
}
.left {
position: absolute;
left: 0;
width: 200px;
height: 200px;
background-color: red;
}
.right {
width: 100%;
height: 200px;
background-color: green;
margin-left: 200px;
}
3.通过flex布局给父级添加display: flex; justify-content: space-between;
.f{
display: flex;
justify-content: space-between;
}
.left {
width: 200px;
height: 200px;
background-color: red;
}
.right {
width: 100%;
height: 200px;
background-color: green;
}
二、三栏布局
我们所常说的三栏布局也叫双飞翼布局/圣杯布局:左右两侧的宽度是固定的,中间部分是自适应的。有了刚才双栏布局的经验,我们可以模仿双栏布局思考。
1.左侧盒子左浮动,右侧盒子右浮动,中间盒子宽度为100%
<div class="f">
<div class="left">left</div>
<div class="right">right</div>
<div class="conter">middle</div>
</div>
看到这块可能很多人会想为什么不可以左中右这样排列,大家可以试着敲一下代码,看一看效果,给大家一个提示:浮动只会影响他后面的盒子,并不会对之前的盒子进行影响
.conter,
.left,
.right {
height: 100px;
opacity: 0.5;
}
.conter {
background-color: red;
margin-left: 100px;
margin-right: 100px;
}
.left {
float: left;
width: 100px;
background: green;
}
.right {
float: right;
width: 100px;
background: yellow;
}
2.通过定位的方式,并给中间盒子设置margin
.f{
position: relative;
}
.conter,
.left,
.right {
height: 100px;
opacity: 0.5;
}
.conter {
background-color: red;
margin-left: 100px;
margin-right: 100px;
}
.left {
position: absolute;
width: 100px;
background: green;
}
.right {
position: absolute;
right:0;
top: 0;
width: 100px;
background: yellow
}
在这个部分,html的结构就需要是正常的左中右了,因为没有了浮动,都是按照标准流的顺序进行排列
<div class="f">
<div class="left">left</div>
<div class="conter">middle</div>
<div class="right">right</div>
</div>
3.flex布局,给父元素添加display:flex,给中间盒子添加flex:1
.f{
display: flex;
}
.conter,
.left,
.right {
height: 100px;
opacity: 0.5;
}
.conter {
background-color: red;
flex:1
}
.left {
width: 100px;
background: green;
}
.right {
width: 100px;
background: yellow
}
在这个部分,html的结构就需要是正常的左中右了,因为没有了浮动,都是按照标准流的顺序进行排列
<div class="f">
<div class="left">left</div>
<div class="conter">middle</div>
<div class="right">right</div>
</div>