如果我有一个带有 position: absolute
的按钮,它位于带有 overflow-x: auto
的 div 中,该按钮将捕捉到容器的边缘。
但是,如果 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 fixed
将不起作用,因为它始终相对于页面。您希望将元素嵌套在另一个具有 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>
关于html - 如何将元素固定在可水平滚动的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57964424/