在页面布局过程中,我们常常会要用到两栏布局或者三栏布局,现在将两栏布局的代码总结如下:
两栏布局通常有以下几种情况:
1.一边宽度固定,一边自适应
2.一边宽度不固定,一边自适应
一边宽度固定,一边自适应:
方法一:左侧float:left;右侧margin-left;
代码 html
<div class="demo">
<div class="left">左</div>
<div class="right">右</div>
</div>
css
*{
padding:0;
margin:0;
}
.demo{
width:500px;
height: 200px;
}
.demo .left{
width:300px;
height: 100%;
float: left;
background-color:#999;
}
.demo .right{
height: 100%;
margin-left: 300px;
background-color: pink;
}
效果图:
方法二:绝对定位:
代码 html
<div class="demo">
<div class="left">左</div>
<div class="right">右</div>
</div>
css:
*{
padding:0;
margin:0;
}
.demo{
position: relative;
width:500px;
height: 200px;
}
.demo .left{
width:300px;
height: 100%;
background-color:#999;
}
.demo .right{
height: 100%;
position: absolute;
top:0;
right:0;
left: 300px;
background-color: pink;
}
效果图:
方法三:左边float:left;右边overflow:hidden;
代码 html
<div class="demo">
<div class="left">左</div>
<div class="right">右</div>
</div>
css:
*{
padding:0;
margin:0;
}
.demo{
width:500px;
height: 200px;
}
.demo .left{
width:300px;
height: 100%;
float: left;
background-color:#999;
}
.demo .right{
height: 100%;
overflow: hidden;
background-color: pink;
}
效果图:
方法四:利用弹性布局:
html:
<div class="demo">
<div class="left">左</div>
<div class="right">右</div>
</div>
css:
*{
padding:0;
margin:0;
}
.demo{
width:500px;
height: 200px;
display: flex;
}
.demo .left{
width:300px;
height: 100%;
background-color:#999;
}
.demo .right{
height: 100%;
flex: 2;
background-color: pink;
}
效果图: