首页 > 解决方案 > 如何将元素固定在水平可滚动的 div 中

问题描述

如果我有一个带有position: absolutediv 内部的按钮,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;
}
<pre class="container">Multi Line Text
Long piece of content that overflows the width of container<button>Copy</button></pre>

标签: htmlcsscss-position

解决方案


位置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;
}
<div class="top-container">
  <button>Copy</button>
  <pre class="container">Long piece of content that overflows the width of container</pre>
</div>


推荐阅读