gpt4 book ai didi

javascript - 如何使用 calc() CSS 计算中间 div(3 div) 的高度

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:23 25 4
gpt4 key购买 nike

是否可以将 css3 的 calc() 函数用于以下用例?我有一个带有特定填充的标题,然后我有一个带有按钮的底部。header 高度和底部高度是固定的,但是介于 header 和 bottom 之间的内容高度需要根据我们提供给容器的高度是动态的

例如:我正在使用 calc() 计算基于 main 类的高度。CSS:

.header {
height: 30px;

background-color: red;
padding: 20px 54px;
}

.bottom {

height: 40px;
background: green;
padding: 60px 54px;
}

.middle-content {
background: blue;
padding: 20px 54px;
height: calc(100% - (300-200)+"px");//height of main class div - (header + bottom)//is this possible to calculate this way

}

.main {
border: 2px solid #000;
width: 100%;
}

html:

<div class="main" style="height:400px">
<div class="header">the header height is fixed and cannot be changed</div>
<div class="middle-content">this div needs to grow/shrink depending on what height we enter in the inline style of "main" class to match up to the height of the main class</div>
<div class="bottom">
the bottom height is fixed and cannot be changed
<button>
Trext1
</button>
<button>
Text333
</button>
</div>
</div>

fiddle : https://jsfiddle.net/95j04gdz/2/

从 fiddle 中您可以看到有一个空白需要由蓝色 div 正确填充以匹配主 div 的高度。有什么想法吗??

最佳答案

当高度是动态的时,您可以使用此代码。

const headerHeight = document.querySelector(".header").offsetHeight;
const bottomHeight = document.querySelector(".bottom").offsetHeight;
const middle = document.querySelector(".middle-content");

middle.style.height = `calc(100% - (${headerHeight}px + ${bottomHeight}px))`;
* {
box-sizing:border-box;
}

.header {
height: 30px;
background-color: red;
padding: 20px 54px;
}

.bottom {

height: 40px;
background: green;
padding: 60px 54px;
}

.middle-content {
background: blue;
padding: 20px 54px;
/*height: calc(100% - (300-200)+"px");*/
/*//height of main class div - (header + bottom)*/
}

.main {
border: 2px solid #000;
width: 100%;
}
<div class="main" style="height:400px">
<div class="header">the header height is fixed and cannot be changed</div>
<div class="middle-content">this div needs to grow/shrink depending on what height we enter in the inline style of "main" class to match up to the height of the main class</div>
<div class="bottom">
the bottom height is fixed and cannot be changed
<button>
Trext1
</button>
<button>
Text333
</button>
</div>
</div>

关于javascript - 如何使用 calc() CSS 计算中间 div(3 div) 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com