1

我已经编写了一个代码片段,以便您更好地理解我的意思。我在网格中有一个可滚动区域。我想在左下角有一个元素来向列表中添加一个新项目。

我希望它相对于可滚动元素定位,因为它将具有动态宽度,这就是为什么我不能只使用固定位置,我不想从屏幕边缘定位它。

我也不希望它与背景一起滚动。有什么方法可以解决这个问题吗?

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

.scrollable {
  background-color: red;
  overflow-y: scroll;
  width: 300px;
  margin: 0 auto;
  position: relative;
}

.item {
  width: 100%;
  border-bottom: 1px solid black;
  height: 90px;
  background-color: blue;
}

.header {
  background-color: yellow;
  width: 100%;
  height: 40px;
}

.footer {
  background-color: yellow;
  width: 100%;
  height: 40px;
}

.add {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  position: absolute;
  bottom: 16px;
  right: 16px;
  background-color: green;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="page">

  <div class="header"></div>

  <div class="scrollable">
    <div class="add">+</div>
    
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  
  <div class="footer"></div>

</div>

4

1 回答 1

1

您可以使用位置sticky将元素“粘贴”到可滚动元素。粘性位置会根据滚动位置在滚动位置static之间波动元素的位置。fixed

由于您不能使用bottomwith position: sticky,因此您必须top改用 ,并且calc()使用按钮的已知高度从顶部开始的边距,在这种情况下30px

.add {
  height: 30px;
  position: sticky;
  float: right; /* go to the right */
  right: 16px;
  top: calc(100% - 30px - 16px);
}
于 2021-06-17T18:27:08.730 回答