我有以下两个页眉和三个页脚的布局:

.my-grid {
    display: grid;
    grid-template-areas:
        "header1"
        "header2"
        "mainAreaExpandMePlease"
        "footer1"
        "footer2"
        "footer3"
        ;
    grid-template-rows: 27px 27px 1fr 28px 28px 28px;
    height: 100%;
}

在显示页眉和页脚后,主区域将展开以填补剩余的空白。
我希望能够打开和关闭页脚(显示/隐藏它们),以便它们折叠。在上面的代码中,隐藏页脚时会在页脚处留下一个间隙。
我该怎么办:
有一个总是扩展的主要区域
具有可选的页眉和页脚,隐藏时可折叠
示例:
如果header1崩溃,那么header2应该取代它,并且mainAreaExpandMePlease应该扩展到以前的header2位置
如果header2塌陷,则mainAreaExpandMePlease应再向上扩展27px
如果footer3塌陷,则footer2取代footer3footer1取代footer2mainAreaExpandMePlease将再向下伸展28px
谢谢您!
小提琴:https://jsfiddle.net/jg6ho4wu/1/
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.my-grid {
    display: grid;
    grid-template-areas:
        "header1"
        "header2"
        "mainAreaExpandMePlease"
        "footer1"
        "footer2"
        "footer3";
    grid-template-rows: 27px 27px 1fr 28px 28px 28px;
    height: 100%;
}

.header1 {
  grid-area: header1;
  background-color: yellow;
}

.header2 {
  grid-area: header2;
  background-color: magenta;
}

.mainAreaExpandMePlease {
  grid-area: mainAreaExpandMePlease;
  background-color: cyan;
}

.footer1 {
  grid-area: footer1;
  background-color: green;
}

.footer2 {
  grid-area: footer2;
  background-color: red;
}

.footer3 {
  grid-area: footer3;
  background-color: blue;
}

<div class="my-grid">
  <div class="header1"></div>
  <div class="header2"></div>
  <div class="mainAreaExpandMePlease"></div>
  <div class="footer1"></div>
  <div class="footer2" style="display:none"></div>
  <div class="footer3"></div>
</div>

最佳答案

不要在容器级别设置页眉和页脚行的高度。
在项目上设置其高度,并将其容器高度设置为auto

.my-grid {
  display: grid;
  height: 100vh;
  grid-template-rows: auto auto 1fr auto auto auto;
  grid-template-areas:  "header1"
                        "header2"
                        "mainAreaExpandMePlease"
                        "footer1"
                        "footer2"
                        "footer3";
}

.header1 {
  height: 27px;
  grid-area: header1;
  background-color: yellow;
}

.header2 {
  height: 27px;
  grid-area: header2;
  background-color: magenta;
}

.mainAreaExpandMePlease {
  grid-area: mainAreaExpandMePlease;
  background-color: cyan;
}

.footer1 {
  height: 28px;
  grid-area: footer1;
  background-color: green;
}

.footer2 {
  height: 28px;
  grid-area: footer2;
  background-color: red;
}

.footer3 {
  height: 28px;
  grid-area: footer3;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
}

<div class="my-grid">
  <div class="header1"></div>
  <div class="header2"></div>
  <div class="mainAreaExpandMePlease"></div>
  <div class="footer1"></div>
  <div class="footer2" style="display:none"></div>
  <div class="footer3"></div>
</div>

09-26 16:07