css - 当网格高度大于页面(设备)高度时,css网格容器出现问题
问题描述
我对 css 网格有疑问,我用 css 网格构建了一个包含两个 div 的容器,我想将容器调整到页面中心。我使用这段代码:
html{
width: 100vw;
height : 100vh;
}
body{
height : 100%;
}
.container-fluid{
width:100%;
height : 100%;
display:grid;
grid-template-columns: 300px;
grid-template-rows: 200px auto;
justify-content: center;
align-content: center;
border:1px solid red;
}
.logo-container{
background-color: khaki;
}
.form-container{
height :540px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/media-query.css">
<title>Login & Register User With Profile</title>
</head>
<body>
<div class="container-fluid">
<div class="logo-container">
<h1>Logo</h1>
</div>
<div class="form-container">
<h1>Form</h1>
</div>
</div>
<link rel="stylesheet" href="assets/css/all.css">
</body>
</html>
如您所见,当网格容器高度大于页面高度时会出现问题(请参阅代码结果)。当使用高度作为正文标签时,网格高度溢出以及从正文标签中删除高度时一切正常,但在此原位容器无法调整页面中心的容器。什么是问题?
解决方案
简化您的代码,如下所示:
body {
margin: 0; /* remove default margin */
}
.container-fluid {
min-height: 100vh; /* at least screen height */
display: grid;
grid-template-columns: 300px;
grid-template-rows: 200px auto;
justify-content: center;
align-content: center;
border: 1px solid red;
box-sizing:border-box; /* to consider the border inside the height */
}
.logo-container {
background-color: khaki;
}
.form-container {
height: 540px;
background-color: lightblue;
}
<div class="container-fluid">
<div class="logo-container">
<h1>Logo</h1>
</div>
<div class="form-container">
<h1>Form</h1>
</div>
</div>
或者像下面这样:
body {
margin: 0;
}
.container-fluid {
height: 100vh; /* full height */
display: grid;
grid-template-columns: 300px;
/* first row at 200px max-height and second row at 540px max-height */
grid-template-rows: minmax(auto,200px) minmax(auto,540px);
justify-content: center;
align-content: center;
border: 1px solid red;
box-sizing:border-box;
}
.logo-container {
background-color: khaki;
}
.form-container {
background-color: lightblue;
}
<div class="container-fluid">
<div class="logo-container">
<h1>Logo</h1>
</div>
<div class="form-container">
<h1>Form</h1>
</div>
</div>
推荐阅读
- c# - 无法将类型 vector3 转换为浮点数
- sql - 使用@@RowCount 进行多次更新
- c - 将指针数组分配给 void 类型转换指针如何工作?
- javascript - React/Redux:当它与 redux-form 结合时,有没有办法清除反应日期选择器?
- go - 如何在使用 GRPC 时提供文件
- ios - 启用物理设备块(Swift)时如何拦截ios旋转?
- javascript - Redux 中更新常量时的延迟
- javascript - 用户更改按钮时隐藏或显示元素
- css - Material UI 使 2 个元素的高度相同
- bash - Bash 脚本不适用于字符串变量,直接在终端中运行良好