首页 > 解决方案 > 当网格高度大于页面(设备)高度时,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>

如您所见,当网格容器高度大于页面高度时会出现问题(请参阅代码结果)。当使用高度作为正文标签时,网格高度溢出以及从正文标签中删除高度时一切正常,但在此原位容器无法调整页面中心的容器。什么是问题?

标签: csscss-grid

解决方案


简化您的代码,如下所示:

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>


推荐阅读