css 如何使块元素填充作为弹性项的父项的可用高度?

tv6aics1  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(84)

亲爱的投票者,请阅读问题之前假设它是一个重复。它与你链接的那个相同。
我不是在问如何扩展一个Flex-item来填充一个Flex容器。我在问如何扩展一个block元素来填充弹性项。
我使用flexbox进行典型的“粘性页脚”布局(页眉,内容,页脚),其中内容区域扩展,所以页脚总是粘在底部。尝试运行以下代码片段:

html,
body {
  margin: 0;
}

.layout {
  background: pink;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

header {
  background: red;
  height: 40px;
}

main {
  background: blue;
  flex: 1;
  position: relative;
}

  .content {
    background: yellow;
    height: 100%;
  }

footer {
  min-height: 60px;
  background: pink;
}
<!doctype html>
<html>
<body>
  <div class="layout">
    <header>
      HEADER
    </header>
    
    <main>
      <div class="content">
        CONTENT
      </div>
    </main>
    
    <footer>
      FOOTER
    </footer>
  </div>
</body>
</html>

蓝色区域(main)是一个带有flex: 1的flex项,它正确地扩展以确保页脚位于视口的底部。
我希望嵌套的黄色块div(.content)填充其父块高度的100%-所以在最终结果中不应该有蓝色可见,因为它应该全部被黄色遮挡。
我做错了什么?

ars1skjm

ars1skjm1#

基于百分比的高度需要一个参考点。main没有定义的高度,你的.layout的高度也没有定义。(min-height不计)。
.layout上的min-height: 100vh更改为height: 100vh,并将height: 100%添加到main

html,
body {
  margin: 0;
}

.layout {
  background: pink;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

header {
  background: red;
  height: 40px;
}

main {
  background: blue;
  flex: 1;
  position: relative;
  height: 100%;
}

.content {
  background: yellow;
  height: 100%;
}

footer {
  min-height: 60px;
  background: pink;
}
<!doctype html>
<html>

<body>
  <div class="layout">
    <header>
      HEADER
    </header>

    <main>
      <div class="content">
        CONTENT
      </div>
    </main>

    <footer>
      FOOTER
    </footer>
  </div>
</body>

</html>
goqiplq2

goqiplq22#

  1. .main { display: flex; flex-direction: column; } + .content { flex: 1 }
    1.或者只是.main { display: grid; }
html,
body {
  margin: 0;
}

.layout {
  background: pink;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

header {
  background: red;
  height: 40px;
}

main {
  background: blue;
  flex: 1;
  position: relative;
  /* 👇 */
  display: flex;
  flex-direction: column;
  /* or */
  /* display: grid; */
}

.content {
  background: yellow;
  flex: 1; /* 👈 */
  /* not need */
  /* height: 100%; */
}

footer {
  min-height: 60px;
  background: pink;
}
<!doctype html>
<html>
<body>
  <div class="layout">
    <header>
      HEADER
    </header>
    
    <main>
      <div class="content">
        CONTENT
      </div>
    </main>
    
    <footer>
      FOOTER
    </footer>
  </div>
</body>
</html>

相关问题