如何将元素固定在可水平滚动的 div 中

How to pin element inside a horizontally scrollable div

如果我在 div 和 overflow-x: auto 的内部有一个带 position: absolute 的按钮,该按钮将吸附到容器的边缘。

但是,如果 div 的内容超出水平宽度,滚动后按钮将固定在容器内的起始位置。

似乎absolute 应该把它固定在一边,但似乎没用

有没有办法将子内容固定到可水平滚动的右侧 div?

最小的、完整的、可验证的示例

.container {
    width: 20rem;
    border: 1px solid grey;
    padding: 1rem 1rem;
    position: relative;
    overflow-x: auto;
}
.container button {
    position: absolute;
    right: 0;
    top: 0;
}
<pre class="container">Multi Line Text
Long piece of content that overflows the width of container<button>Copy</button></pre>

我最接近的是使用 position: sticky

.container {
    width: 20rem;
    border: 1px solid grey;
    padding: 1rem 1rem;
    position: relative;
    overflow-x: auto;
}
.container button {
    position: sticky;
    right: 0;
    top: 0;
}
<pre class="container">Long piece of content that overflows the width of container<button>Copy</button></pre>

位置 fixed 将不起作用,因为它始终相对于页面。您想要将元素嵌套在另一个具有位置 relative 的组件中。里面的元素会根据这个parent来定位。

.top-container {
    position: relative;
    width: 20rem;
    border: 1px solid grey;
}

.container {
    padding: 1rem 1rem;
    overflow-x: auto;
    margin: 0;
}
.top-container button {
    position: absolute;
    right: 0;
    top: 0;
}
<div class="top-container">
  <button>Copy</button>
  <pre class="container">Long piece of content that overflows the width of container</pre>
</div>