【问题标题】:Make an element scroll inside a grid section使元素在网格部分内滚动
【发布时间】:2021-11-28 00:02:14
【问题描述】:

我正在尝试在我的 div 中创建一个可滚动区域,如下图所示。我只希望可滚动区域在不同的屏幕高度上改变高度并相应地滚动。

问题是,如果可滚动内容大到可以滚动,它会使整个页面滚动。如果它很小,页脚会正确地停留在底部。

这是我目前所拥有的

* {
  margin: 0;
  padding: 0;
  width: 100%;
}

.container {
  display: grid;
  grid-template-rows: auto 1fr auto;
  height: 100vh;
}

.header {
  height: 30px;
  background-color: lightblue;
}

.footer {
  height: 30px;
  background-color: lightblue;
}

.content {
  display: grid;
  grid-template-rows: auto 1fr;
}

.profile {
  height: 60px;
  background-color: lightpink;
}

.tabs {
  height: 20px;
  background-color: lightgreen;
}

.scroller {
  background-color: cyan;
  height: 100%;
  overflow-y: scroll;
}

.scrollable-content {
  background-color: yellow;
  width: 200px;
  height: 600px;
  margin: 0 auto;
  position: relative;
}

span {
  bottom: 0;
  left: 0;
  position: absolute;
}
<div class="container">

  <div class="header">Header</div>
  
  <div class="content">
    <div class="profile">Profile</div>
    <div class="tab-control">
      <div class="tabs">Tabs</div>
      <div class="scroller">
        <div class="scrollable-content">scrollable content<span>end</span></div>
      </div>
    </div>
  </div>
  
  <div class="footer">Footer</div>

</div>

任何帮助都是appriciated

【问题讨论】:

    标签: html css css-grid


    【解决方案1】:

    如果您将某些元素设置为具有overflow: hidden;,它会起作用。为.container.content.tab-control 设置它

    .container, .content, .tab-control {
      overflow: hidden;
    }
    

    .scroller 元素会有一个小问题,它的一部分将被页脚覆盖。

    要解决这个问题,也可以添加:

    .tab-control {
      display: flex;
      flex-direction: column;
    }
    
    .scroller {
      flex: 100% 1 1;
    }
    

    【讨论】:

    • 完美!谢谢你
    【解决方案2】:

    在滚动条上设置固定高度。 100vh = 浏览器高度 - 140px(页面上所有其他元素的累积高度)

    在你想要滚动的栏上设置overflow-y: auto,你可以将.scrollable-content的高度设置为你想要的任意大。

    .scroller {
      background-color: cyan;
      height: calc(100vh - 140px);
      overflow-y: scroll;
    }
    
    .scrollable-content {
      background-color: yellow;
      width: 200px;
      height: 600px;
      margin: 0 auto;
      position: relative;
      overflow-y: auto;
    }
    

    【讨论】:

    • 但是看看,如果任何其他元素改变高度,滚动条也需要每次更新。
    • 我不明白为什么会这样它上面的所有元素的设计。如果您正在寻找根据内容更改动态更新 .scoller 的解决方案,请使用 javascript。
    • Css Grid 应该能够自动确定滚动条高度,因为容器是 100vh。该解决方案在没有网格的情况下是正确的,但网格可以实现,因此您不必更新多个位置并自动检测。我不确定为什么我的网格示例不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多