CSS网格不适合其父div的高度

时间:2019-03-22 10:26:34

标签: html html5 css3 layout css-grid

我构建了一个CSS网格布局,其中包含标题,sider和一些可滚动的内容。

我正在尝试在设置divwidth的容器height中测试该布局。

布局对容器的width响应良好,但对height的响应却很好,为什么会这样,并且有办法修复它?

body {
  margin: 0;
}

.container {
  width: 70%;
  height: 300px; /* How can I set the height? */
}
.page {
  width: 100%;  
  display: grid;  
  grid-template-rows: 55px calc(100vh - 55px); /* height limitation on second row */
  grid-template-columns: 200px auto;
  grid-template-areas:
    "nav header"
    "nav content";
}

.nav {
  grid-area: nav;
  background-color: aqua;
}

.header {
  grid-area: header;
  background-color: grey;
}

.content {
  grid-area: content;
  background-color: red;
  overflow-y: auto; /* overflow condition on parent */
}

article {
  height: 1000px; /* height set on child; triggers scroll */
}
<div class="container">
  <div class="page">
    <div class="nav">Side nav</div>
    <div class="header">Header</div>
    <div class="content">
      <article>
        <!-- new section for content -->
        <h1>title</h1>
        <p>A lot of content, simulated by .article height: 1000px</p>

      </article>
    </div>
  </div>

1 个答案:

答案 0 :(得分:1)

您必须为网格容器设置显式高度,然后从calc中移除grid-template-rows并将其设置为1fr第二行。

因此,您可以将height: 100%设置为page(以使其继承container的高度)并使用grid-template-rows: 55px 1fr(现在第二行展开以适应剩余高度)。参见下面的演示:

body {
  margin: 0;
}

.container {
  width: 70%;
  height: 300px; /* How can I set the height? */
}
.page {
  width: 100%; 
  height: 100%; /* added */ 
  display: grid;  
  grid-template-rows: 55px 1fr; /* changed */
  grid-template-columns: 200px auto;
  grid-template-areas:
    "nav header"
    "nav content";
}

.nav {
  grid-area: nav;
  background-color: aqua;
}

.header {
  grid-area: header;
  background-color: grey;
}

.content {
  grid-area: content;
  background-color: red;
  overflow-y: auto; /* overflow condition on parent */
}

article {
  height: 1000px; /* height set on child; triggers scroll */
}
<div class="container">
  <div class="page">
    <div class="nav">Side nav</div>
    <div class="header">Header</div>
    <div class="content">
      <article>
        <!-- new section for content -->
        <h1>title</h1>
        <p>A lot of content, simulated by .article height: 1000px</p>

      </article>
    </div>
  </div>