二栏布局分为以下几种情况
- 一栏固定宽度,一栏自适应
- 一栏不定宽,一栏自适应
- 两栏等高
- 左右宽度比为1:2,右边又分为上下结构,高度比为1:1
一栏固定宽度,一栏自适应
方法一:浮动布局
左侧设置float:left,右侧设置margin-left为左侧的宽度。右侧不能设置float:left。
两个div 右边div设置样式 {宽度:300px,左浮动}
左边div设置样式{左边外边距300px}右侧主要内容则用margin-left留出左侧栏的宽度,默认宽度为auto,自动填满剩下的宽度。
<style type="text/css">
#left{
width:500px;
height:300px;
float:left;
background:red;
}
#right{
height:300px;
margin-left:500px;
background:blue;
}
</style>
方法二: 左侧设置float:left,右侧设置overflow:hidden。
利用的是创建一个新的BFC(块级格式化上下文)来防止文字环绕的原理来实现的。BFC就是一个相对独立的布局环境,它内部元素的布局不受外面布局的影响。
<style type="text/css">
#left{
width:500px;
height:300px;
float:left;
background:red;
}
#right{
height:300px;
overflow:hidden;
background:blue;
}
</style>
方法三: 左侧设置绝对定位,偏移量都为0,右侧设置margin-left为左边的宽度。
#left{
width:500px;
height:300px;
position:absolute;
left:0px;
top:0px;
background:red;
}
#right{
height:300px;
margin-left:500px;
background:blue;
}
方法四: 父元素设置display:flex,右侧设置flex:1
<style type="text/css">
body{
display:flex;
}
#left{
width:500px;
height:300px;
background:red;
}
#right{
height:300px;
flex:1;
background:blue;
}
</style>
2、右侧固定宽度,左侧自适应
方法一: 左侧设置margin-right为右侧的宽度,右侧设置float:right。
<style type="text/css">
#left{
height:300px;
margin-right:300px;
background:red;
}
#right{
width:500px;
height:300px;
float:right;
background:blue;
}
</style>
注意非浮动盒子要在浮动盒子的后面,因为如果在前面,那么非浮动盒子的排斥性,会让浮动盒子的内容到下一行
方法二: 左侧设置margin-right为右侧的宽度,右侧采用绝对定位,根据所需的右侧div与浏览器窗口的顶端和右边的距离分别设置top和right。
<style type="text/css">
body{
margin:0;
}
#left{
height:300px;
margin-right:500px;
background:red;
}
#right{
width:500px;
height:300px;
position:absolute;
top:0;
right:0;
background:blue;
}
</style>
注意:因为body有默认的magin,所以定位时会有间隙,所以style中要先清除body的外边距
方法三: 左侧设置width为100%,float: left,margin-right为右侧的宽度的负值,右侧设置float: right。
<style type="text/css">
#left{
height:300px;
float:left;
width:100%;
margin-right:-500px;
background:red;
}
#right{
width:500px;
height:300px;
float:right;
background:blue;
}
</style>
方法四: 父元素设置display:flex,左侧设置flex:1。
<style type="text/css">
body{
display:flex;
}
#left{
height:300px;
flex:1;
background:red;
}
#right{
width:500px;
height:300px;
background:blue;
}
</style>
三栏布局
左右固定宽度,中间自适应
方法一:左侧设置float:left,右侧设置float:right,中间设置margin-right为右侧的宽度,margin-left为左侧的宽度。
<style type="text/css">
#left{
width:200px;
height:300px;
float:left;
background:red;
}
#middle{
height:300px;
margin-left:200px;
margin-right:500px;
background:blue;
}
#right{
width:500px;
height:300px;
float:right;
background:red;
}
</style>
</head>
<body>
<div id="left"></div>
<div id="right"></div>
<div id="middle"></div>
</body>
注意:需要把right放在middle的前面。
方法二: 中间设置margin-right为右侧的宽度,margin-left为左侧的宽度,左侧和右侧采用绝对定位,根据左侧div所需的left与浏览器窗口的顶端和左边的距离分别设置top和left,根据所需的右侧div与浏览器窗口的顶端和右边的距离分别设置top和right。