一般两栏布局指的是左边一栏宽度固定,右边一栏宽度自适应,两栏布局的具体实现:
浮动
- 将左边元素宽度设置为
200px,并且设置向左浮动。将右边元素的margin-left设置为200px,宽度设置为auto(默认为auto,撑满整个父元素)
<style>
.container {
height: 100px;
}
.left {
float: left;
width: 200px;
height: 100%;
background: tomato;
}
.right {
height: 100%;
margin-left: 200px;
background: gold;
}
</style>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
- 利用浮动,左侧元素设置固定大小,并开启左浮动,右侧元素设置
overflow: hidden;这样右侧元素就创建了BFC,利用创建了BFC区域的元素不会与浮动元素发生重叠的特性来让其与左浮动元素分割开来,最终实现两栏布局的效果
.container {
height: 100px;
}
.left {
float: left;
width: 200px;
height: 100%; // 浮动元素height设置为100%后继承的依然是父元素的高度
background: tomato;
}
.right {
overflow: hidden;
height: 100%;
background: gold;
}
flex布局(最常用)
- 利用
flex布局,flex的默认值是0 1 auto;为了让左边宽度固定,所以必须要把flex-shrink的值更改为0。为了让右侧元素自适应,所以其flex属性需要设置为1(1 1 0%)
由于align-items属性默认值为strench,所以开启了flex布局的子元素不设置高度也会被拉伸至和父元素等高
.container {
display: flex;
height: 100px;
}
.left {
flex: 0 0 200px;
background: tomato;
}
.right {
flex: 1;
background: gold;
}
grid布局
-
利用
grid布局,将整体布局分为两列,第一列宽度设置为200px,第二列宽度设置为自适应即可实现基本的两栏布局。作为一个较新的特性,其主要适用于二维布局的场景中,功能十分强大,合理使用将会大大减少我们的代码
.container { display: grid; grid-template-columns: 200px 1fr; height: 100px; } .left { background-color: red; } .right { background-color: yellow; }
#### 绝对定位
1. 利用绝对定位,将父级元素设置为相对定位。左边元素设置为`absolute`定位,并且宽度设置为`200px`。将右边元素的`margin-left`的值设置为`200px`
```css
.container {
position: relative;
}
.left {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 100%;
background: tomato;
}
.right {
height: 100px;
margin-left: 200px;
background: gold;
}
- 利用绝对定位,将父级元素设置为相对定位。左边元素宽度设置为
200px,右边元素设置为绝对定位,left值设为200px,其余方向定位为0
注意:我们不需要给right设置高度,但要将top、bottom、right的值设为0,这样才可以保证最终元素是紧贴父元素顶部、底部和右侧的,left设为200px的目的是为了让其不要被left所覆盖
.container {
position: relative;
}
.left {
width: 200px;
height: 100px;
background: tomato;
}
.right {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 200px;
background: gold;
}
table布局
父级元素设置CSS属性 display: table,并设置宽度 100%;左边元素设置CSS属性 display: table-cell,并设置固定宽度;右边元素设置CSS属性 table-cell 即可
.container {
display: table;
width: 100%;
}
.left {
display: table-cell;
width: 200px;
height: 200px;
background: tomato;
}
.right {
display: table-cell;
background: gold;
height: 200px;
}
使用 calc 函数
左边元素设置CSS属性 float: left,并设置固定宽度;右边元素设置CSS属性 float: left 并设置宽度 width,其值等于 calc(100% - 左侧元素的宽度)
.container {
width: 100%;
height: 500px;
}
.left {
float: left;
width: 240px;
height: 100%;
background-color: tomato;
}
.right {
float: left;
width: calc(100% - 240px);
height: 100%;
background-color: gold;
}
以上所有方法的效果图都如下所示: