网格项目的父级高度为100%

时间:2019-10-21 14:26:59

标签: css css-grid

此页面中的红色侧栏必须为容器高度的100%:

body {
  display: grid;
  min-height: 85vh;
  grid-template-columns: auto 10fr 4fr;
  grid-template-rows: minmax(1rem, max-content) 1fr minmax(1rem, max-content);
  grid-template-areas: "header header aside" "main main aside" "footer footer footer";
}

header {
  grid-area: header;
  background: pink;
}

footer {
  grid-area: footer;
  background: blue;
}

main {
  grid-area: main;
  background: green;
}

aside {
  grid-area: aside;
  background: red;
  height: 100px;
  overflow-y: scroll;
}
<header> header </header>
<main>main</main>
<aside>
  aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>
</aside>
<footer> footer </footer>

是否可以在不添加绝对高度为100%的其他内部元素的情况下实现?

请注意,我为它添加了100px的高度,只是指出它需要可滚动。但我希望高度为容器的100%...

2 个答案:

答案 0 :(得分:3)

使用min-height: 100%;height:0;来避免边的高度影响布局,然后同时将其强制为100%的高度(其他内容所定义的轨迹高度)

body {
  display: grid;
  min-height: 85vh;
  grid-template-columns: auto 10fr 4fr;
  grid-template-rows: 
    minmax(1rem, max-content) 1fr minmax(1rem, max-content);
  grid-template-areas: 
    "header header aside" 
    "main   main   aside" 
    "footer footer footer";
}

header {
  grid-area: header;
  background: pink;
}

footer {
  grid-area: footer;
  background: blue;
}

main {
  grid-area: main;
  background: green;
}

aside {
  grid-area: aside;
  background: red;
  min-height: 100%;
  height:0;
  overflow-y: scroll;
}
<header> header </header>
<main>main</main>
<aside>
  aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>
</aside>
<footer> footer </footer>

答案 1 :(得分:1)

您可以添加在网格容器上使用的确切高度,然后添加overflow-y: scroll

body {
  display: grid;
  min-height: 75vh;
  grid-template-columns: auto 10fr 4fr;
  grid-template-rows: minmax(1rem, max-content) 1fr minmax(1rem, max-content);
  grid-template-areas: "header header aside" "main main aside" "footer footer footer";
}

header {
  grid-area: header;
  background: pink;
}

footer {
  grid-area: footer;
  background: blue;
}

main {
  grid-area: main;
  background: green;
}

aside {
  height: 100%;
  grid-area: aside;
  background: red;
  max-height: 75vh;
  overflow-y: scroll;
  z-index: 1;
}
<header> header </header>
<main>main</main>
<aside>
  aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>aside<br>
</aside>
<footer> footer </footer>