【CSS】一个div宽度或高度固定,另一个div铺满剩余空间

如果我们想实现下图的效果(一行中放两个div,左边的一个div宽度固定,右边的div横向铺满):

首先我们先写三个div:父div包裹两个div。

left

right

且给三个div添加最基本样式:外层宽度100%,左边div固定宽度,右边div不给宽度(默认100%)

.content {

width: 100%;

height: 200px;

}

.left {

width: 100px;

height: 100%;

background: red;

}

.right {

background: blue;

height: 100%;

}

现在的效果如下:

下面来介绍一下如何实现一个div宽度固定,另一个div铺满剩余空间:

方法1:用flex布局:

给content添加 display: flex; 属性,给 right 添加 flex: 1; 属性。

.content {

/* ... */

display: flex;

}

/* ... */

.right {

/* ... */

flex: 1;

}

小tips:如果右边div中的内容过长,造成左边固定宽度的div压缩了,可以用下面两个方案解决:

方案1:给 right 添加 width: 0; 属性。

方案2:给 left 添加 flex-shrink: 0; 属性。

方法2:用浮动布局和overflow属性:

给left添加 float: left; 属性,给right添加 overflow: hidden; 属性。

/* ... */

.left {

/* ... */

float: left;

}

.right {

/* ... */

overflow: hidden;

}

方法3:用浮动和左边距:

给left添加 float: left; 属性,给right添加 margin-left: 100px; 属性。

/* ... */

.left {

/* ... */

float: left;

}

.right {

/* ... */

margin-left: 100px;

}

如果我们想实现下图的效果(一列中放两个div,上面的div高度固定,下面的div竖向铺满):

首先我们先写三个div:父div包裹两个div。

top

bottom

且给三个div添加最基本样式:外层高度设置成300px,上面div固定高度,下面div不给高度(默认不是100%)

.content {

width: 200px;

height: 300px;

border: 1px solid black;

}

.top {

width: 100%;

height: 100px;

background: red;

}

.bottom {

width: 100%;

background: blue;

}

现在的效果如下:

下面来介绍一下如何实现一个div高度固定,另一个div铺满剩余空间:

方法1:用flex布局:

给content添加 display: flex;flex-direction: column; 属性,给bottom添加 flex: 1; 属性。

.content {

/* ... */

display: flex;

flex-direction: column;

}

/* ... */

.bottom {

/* ... */

flex: 1;

}

方法2:用calc设置高度:

给bottom添加 height: calc(100% - 100px); 属性。

/* ... */

.bottom {

/* ... */

height: calc(100% - 100px);

}

方法3:用绝对定位:

给content添加 display: relative; 属性,给bottom添加 position: absolute; top: 100px; bottom: 0; 属性。

.content {

/* ... */

position: relative;

}

/* ... */

.bottom {

/* ... */

position: absolute;

top: 100px;

bottom: 0;

}