我最近遇到了一个奇怪的 CSS 行为,我试图了解发生了什么,但我想我错过了一些关于导航器中渲染引擎的知识。
代码在codepen:https://codepen.io/ghivert/pen/mdyEZpe .
有关信息,代码也在下面:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i&display=swap" rel="stylesheet">
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<div class="grid">
<header>Header</header>
<nav>Navbar</nav>
<main>
<div class="content">Main Content</div>
<footer>Footer</footer>
</main>
</div>
</body>
</html>
* {
box-sizing: border-box;
}
html {
line-height: 1.15;
font-family: Poppins,Helvetica,sans-serif
}
body {
margin: 0;
}
.grid {
display: grid;
grid-template-areas:
"navbar header"
"navbar central";
grid-template-columns: auto 1fr;
grid-template-rows: auto 1fr;
height: 100vh;
overflow: hidden;
}
header {
grid-area: header;
background: lemonchiffon;
}
nav {
grid-area: navbar;
background: blue;
}
main {
grid-area: central;
display: grid;
grid-template-areas:
"content" "footer";
grid-template-rows: 1fr auto;
background: purple;
overflow: auto;
}
footer {
grid-area: footer;
background: red;
}
如果您看一下代码笔,中央网格上的溢出比我预期的要多一些。 <main>
里面的尺寸不完全<div>
和 <footer>
, 它高了一些像素。
我发现它来自 line-height: 1.15;
的组合和 Poppins 字体系列。当我删除行高或 Poppins 时,它按预期工作,<main>
底部没有额外空间。 .
您能解释一下为什么会发生这种行为吗?避免在未来数小时内对其进行调试。
编辑:
加个图看得更清楚:
我说的是红色页脚下方的白线。
最佳答案
空间是由grid-template-rows: 1fr auto;
引起的在 <main>
.您正在使用 auto
.在 CSS-Grid 中,grid-template-rows 值 auto
意思是:
The size of the rows/column is determined by the size of the container, and on the size of the content of the items in the row
换句话说,页脚需要知道它的高度,因为网格没有定义它。
通过给页脚一个高度值来修复它。
footer {
grid-area: footer;
background: red;
height: 20px;
}
或
main {
grid-area: central;
display: grid;
grid-template-areas:
"content" "footer";
grid-template-rows: 1fr 20px;
background: green;
overflow: auto;
}
当心,使用px
, em
或 vh
.它将变为自动的百分比。
CSS-Grid 中的百分比
Is a non-negative value, relative to the block size of the grid container. If the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto.
关于html - Poppins 和行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321362/