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

Kyl*_*Mit 0 html css css-position

如果我position: absolute在div的内部有一个按钮,则overflow-x: auto该按钮将对齐容器的边缘。

但是,如果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;
}
Run Code Online (Sandbox Code Playgroud)
<pre class="container">Multi Line Text
Long piece of content that overflows the width of container<button>Copy</button></pre>
Run Code Online (Sandbox Code Playgroud)

Loï*_*ord 5

位置fixed无效,因为它总是相对于页面。您想将元素嵌套在另一个具有position的组件中relative。内部元素将基于该父元素定位。

.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;
}
Run Code Online (Sandbox Code Playgroud)
<div class="top-container">
  <button>Copy</button>
  <pre class="container">Long piece of content that overflows the width of container</pre>
</div>
Run Code Online (Sandbox Code Playgroud)