如何将元素固定在水平滚动的div中 [英] How to pin element inside a horizontally scrollable div

查看:72
本文介绍了如何将元素固定在水平滚动的div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在具有 overflow-x:auto 的div内有一个 position:absolute 的按钮,则该按钮将捕捉到容器的边缘.

If I have a button with position: absolute inside of a div with overflow-x: auto the button will snap to the edge of the container.

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

However, if the div's content overflows the horizontal width, the button stays pinned to its starting location within the container after scrolling.

似乎 absolute 应该将其固定在一边,但似乎并不能解决问题

It seems absolute ought to fix it to the side, but doesn't seem to do the trick

有什么方法可以将子内容固定在水平滚动div的右侧吗?

Is there any way to pin the child content to the right side of a horizontally scrollable 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>

推荐答案

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

Position fixed won't work because it's always relative to the page. You want to nest the elements inside another component that has a position relative. The elements inside will be positioned based on this 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>

这篇关于如何将元素固定在水平滚动的div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆