根据页眉和页脚高度计算身体高度

问题描述 投票:0回答:1

我的标题带有

height: 8rem;

.header {
    top: 0;
    left: 0;
    height: 8rem;
}

然后我有一个页脚

height: 5rem;

footer
{
    width:100%; 
    height: 5rem;    
}

我正在尝试计算主体内容的高度以适合 100% 屏幕的高度。我想出的是

.body-content{
  height: calc(100vh - 8rem - 5rem);
}

但是这不起作用,并且高度比屏幕长。经过反复试验,最完美的方法是:

.body-content{
  height: calc(100vh - 15.5rem);
}

但是不应该是100%屏幕高度-页眉高度-页脚高度吗?

css
1个回答
0
投票

没有人可以使用您共享的信息来判断您的布局出了什么问题,但看起来您正在尝试构建一个网页,其顶部标题高度为 8rem,底部页脚高度为 5rem,这些元素之间的内容为高度足以填充视口中的所有剩余空间。

我想建议您采用不同的方法,使用 css

display: flex
属性。

运行以下代码片段:

html, body {
  height: 100%;
  margin: 0;
}

body {
  /* this does the magic */
  display: flex;
  flex-direction: column;
  margin: 0;
}

.header {
  /* fixed height, no shrink */
  height: 8rem;
  flex-shrink: 0;
  
  background: #f5f5f5;
  margin: 0;
}

.footer {
  /* fixed height, no shrink */
  height: 5rem;
  flex-shrink: 0;
  
  background: #f5f5f5;
  margin: 0;
}

.body-content {
  /* variable height, scroll content if needed */
  flex: 1;
  overflow: auto;
  
  background: #e5e5e5;
  margin: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Flex Layout Example</title>
</head>
<body>
  <header class="header">Header</header>
  <main class="body-content">Content</main>
  <footer class="footer">Footer</footer>
</body>

Flexbox 是设计布局的现代方式,您可以访问以下页面了解所需的所有内容:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

© www.soinside.com 2019 - 2024. All rights reserved.