【问题标题】:How to make child with position absolute scroll with parent?如何使具有位置绝对滚动的孩子与父母一起?
【发布时间】:2021-04-18 18:34:39
【问题描述】:

我想在可滚动的 div 和绝对位置子按钮中直接放置按钮,但不在可滚动的 div 内。

当我滚动包含按钮的 div 时,我希望按钮下方的内容(蓝色方块)也随着 div 滚动,因此蓝色方块始终位于按钮的正下方。就像现在一样,蓝色方块总是停留在同一个地方。但是,当我将父位置设为相对位置时,蓝色方块在可滚动 div 内(带有黑色边框的那个),我想要它在外面。

<div style="width: 500px; height: 50px; border: 2px solid black; overflow-x: auto; overflow-y: hidden; white-space: nowrap;">
    <div style="display: inline-block; width: 250px;">
       <button style="width: 100%; height: 100%;">Hello</button>
       <div style="position: absolute; background-color: blue; width: 50px; height: 50px;"></div>
    </div>
    <div style="display: inline-block; width: 250px;">
       <button style="width: 100%; height: 100%;">Hello</button>
       <div style="position: absolute; background-color: blue; width: 50px; height: 50px;"></div>
    </div>
    <div style="display: inline-block; width: 250px;">
       <button style="width: 100%; height: 100%;">Hello</button>
       <div style="position: absolute; background-color: blue; width: 50px; height: 50px;"></div>
    </div>
    <div style="display: inline-block; width: 250px;">
       <button style="width: 100%; height: 100%;">Hello</button>
       <div style="position: absolute; background-color: blue; width: 50px; height: 50px;"></div>
    </div>
</div>

有没有人知道如何进行这项工作?我正在查看stackoverflow,但没有帮助,我认为我对定位非常了解,但可能还不够好。如果您知道如何修复定位或以完全不同的方式进行定位,我将不胜感激:)

【问题讨论】:

  • 容器height: 50px;是否有意在黑框外显示框?

标签: html css scroll css-position


【解决方案1】:

您可以absolute 将蓝色框relative 定位到父容器,并添加top: 100%; 以将它们与容器底部对齐。

另外请使用 CSS 而不是内联样式,这有助于轻松阅读了解发生了什么。

body {
  overflow: hidden;
}

.container {
  width: 100%;
  height: 100px;
  border: 2px solid black;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

.box {
  display: inline-block;
  position: relative;
  width: 250px;
  height: 50px;
  margin: 5px;
  background: dodgerblue;
}

.bluebox {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 100%;
  background-color: blue;
}
<div class="container">
  <div class="box">
    <button>Hello</button>
    <div class="bluebox"></div>
  </div>
  <div class="box">
    <button>Hello</button>
    <div class="bluebox"></div>
  </div>
  <div class="box">
    <button>Hello</button>
    <div class="bluebox"></div>
  </div>
  <div class="box">
    <button>Hello</button>
    <div class="bluebox"></div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多