学无先后,达者为师

网站首页 编程语言 正文

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

作者:qing_小诺 更新时间: 2022-04-11 编程语言

如果我们想实现下图的效果(一行中放两个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;
}

方法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;
}

 

原文链接:https://blog.csdn.net/qq_33237207/article/details/100102757

栏目分类
最近更新