一、两栏布局
左边宽度固定,右边宽度自适应
1.1 实现方法总结
- 左侧浮动+ margin-left(右侧)
- 左侧浮动 + 右侧overflow: hidden
- 左侧绝对定位 + margin-left(右侧)
- 右侧绝对定位(left为左侧宽度,必须设置top、bottom、right为0)
- 父级元素flex布局,右侧flex:1 (自动放大占满剩余空间)
html结构如下:
<div class="contain">
<div class="left"></div>
<div class="right"></div>
</div>
1、左侧浮动+ margin-left
.contain {
height: 300px;
}
.left {
float: left;
height: 100%;
width: 200px;
background-color: pink;
}
.right {
overflow: hidden;
height: 100%;
background-color: blue;
}
1.2 左侧浮动+ 右侧overflow: hidden
.contain {
height: 300px;
}
.left {
float: left;
height: 100%;
width: 200px;
background-color: pink;
}
.right {
overflow: hidden;
height: 100%;
background-color: blue;
}
1.3 左侧定位+ margin-left(右侧)
.contain {
height: 300px;
position: relative;
}
.left {
position: absolute;
height: 100%;
width: 200px;
background-color: pink;
}
.right {
margin-left: 200px;
height: 100%;
background-color: blue;
}
1.4 右侧定位(left为左侧宽度)
.contain {
height: 300px;
position: relative;
}
.left {
height: 100%;
width: 200px;
background-color: pink;
}
.right {
position: absolute;
left: 200px;
top: 0;
bottom: 0;
right: 0;
height: 100%;
background-color: blue;
}
1.5 父元素flex布局,右侧flex:1
.contain {
height: 300px;
display: flex;
}
.left {
height: 100%;
width: 200px;
background-color: pink;
}
.right {
flex: 1;
left: 200px;
height: 100%;
background-color: blue;
}
二、三栏布局
2.1 浮动实现
经典的三栏布局分为常见的双飞翼布局和圣杯布局,都是中间宽度自适应,两侧宽度固定
区别: 双飞翼布局是通过margin实现,圣杯布局是通过padding实现
圣杯布局:三者都浮动,外容器在padding中留出左右两边的宽度,利用相对定位定位出来
双飞翼布局:三者都浮动,利用margin实现,没有采用相对定位
2.1.1 圣杯布局
<div class="contain">
<!-- 优先渲染center,将它放在最前面 -->
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
* {
padding: 0;
margin: 0;
}
.contain {
overflow: hidden;
padding: 0 220px 0 200px;
height: 400px;
}
body {
min-width: 700px;
}
.center,
.left,
.right {
float: left;
height: 100%;
}
.center {
width: 100%;
background-color: pink;
}
.left {
width: 200px;
background-color: skyblue;
margin-left: -100%;
position: relative;
right: 200px;
}
.right {
width: 220px;
background-color: blue;
margin-right: -220px;
}
2.1.2 双飞翼布局
<div class="contain">
<div class="center">
<div class="content">中间</div>
</div>
<div class="left">左边</div>
<div class="right">右边</div>
</div>
.contain {
height: 500px;
overflow: hidden;
}
.center,
.left,
.right {
float: left;
height: 100%;
}
.center {
width: 100%;
background-color: pink;
}
.left {
width: 220px;
background-color: skyblue;
margin-left: -100%;
}
.right {
width: 200px;
background-color: red;
margin-left: -200px;
}
.content {
margin: 0 200px 0 220px;
}
2.2 flex布局实现
flex布局下圣杯和双飞翼布局实现方法一样
.contain {
display: flex;
height: 200px;
}
.left {
width: 100px;
height: 100%;
order: -1;
background-color: red;
}
.right {
width: 200px;
height: 100%;
background-color: blue;
}
.center {
flex: 1;
background-color: pink;
}