html - 如何将元素固定在水平可滚动的 div 中
问题描述
如果我有一个带有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;
}
<pre class="container">Multi Line Text
Long piece of content that overflows the width of container<button>Copy</button></pre>
解决方案
位置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>
推荐阅读
- xml - 从特定 XML 文件格式构建 TreeView
- cmake - CMake 错误:包含找不到加载文件:目标
- java - Future 上未捕获的异常:通用 conv 实现目前不支持分组卷积
- react-hooks - 如何让 React Fabric UI 上的 DetailsList/Selection 组件与 ReactHooks 一起使用?
- reactjs - 将焦点设置在有状态组件中的特定按钮上的反应方式?
- java - Java SDK 中的 Amazon S3 KMS 上传
- tensorflow - TensorFlow print_selective_registration_header 构建中的 absl 依赖问题
- c# - 如何通过 asp-... 标签发送我的选择列表值?
- cookies - 将 EDN/Map 读/写到 cookie 中
- file-upload - 什么通常会导致“uwsgi-body-read:...Client closed connection”错误?