[前端面试题]flex上下布局
[万字长文]一文教你彻底搞懂flex布局
[CSS]一些flex的应用场景
页面中有两个元素。元素bottom固定在底部,靠内容来撑开;而元素top在上边,高度自适应,自动铺满除bottom剩下的空间,且top内容是可以滚动的,如何用css的flex布局实现呢。
![[前端面试题]flex上下布局 [前端面试题]flex上下布局](https://www.yuucn.com/wp-content/uploads/2023/04/1682181950-b6d606ff078889b.png)
使用 CSS 的 Flex 布局来实现这个效果可能需要一些额外的步骤。
在容器上应用 display:flex 和 flex-direction:column,并在bottom上应用 flex-shrink:0,以便它不会收缩。然后,可以为元素top设置 flex-grow:1,这将使它在容器中占据剩余的空间。
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <style>
      .main {
        display: flex;
        flex-direction: column;
        border: 1px solid black;
        height: 90vh;
      }
      .top {
        flex-grow: 1;
        /*或者用flex: 1;*/
        overflow: scroll;
      }
      .bottom {
        flex-shrink: 0;
      }
    </style>
  </head>
  <body>
    <div class="main">
      <div class="top">
        <div style="height: 2000px; background: red"></div>
      </div>
      <div class="bottom">
        <div style="height: 100px; background: green"></div>
      </div>
    </div>
  </body>
</html>
flex的默认值为flex:0 1 auto。flex:1相当于设置了flex:1 1 auto。flex-grow属性为1,该元素将会占据容器中所有的剩余空间,所以可以轻易地做到footer元素一直保持在底部的效果。