【问题标题】:CSS grid does not fit its parent div's heightCSS 网格不适合其父 div 的高度
【发布时间】:2019-08-13 07:40:10
【问题描述】:

我构建了一个带有标题、边栏和一些可滚动内容的 CSS 网格布局。

我正在尝试在容器 div 中测试该布局,我在其中设置了 widthheight

布局对容器的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>

【问题讨论】:

    标签: html css layout css-grid


    【解决方案1】:

    您必须为网格容器设置显式高度,然后从grid-template-rows 中删除calc,并将其设置为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>

    【讨论】:

    • fr 单元确实是一个更好的选择,谢谢!使用fr 而不是auto 总是更好的选择吗?我想知道我是否也应该写:grid-template-columns: 200px 1fr;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多