如何让设置position:sticky的按钮始终固定在右上角?
让position:sticky按钮固定在右上角的解决方法
你当前的代码中,position: sticky的right: 0在水平方向未生效,核心原因是sticky元素的水平定位需要先让元素本身处于容器的水平右侧位置,否则right属性没有触发的空间。
修改后的代码
CSS
div { background-color: red; overflow: auto; height: 20rem; width: 20rem; } input { background-color: blue; position: sticky; top: 0; right: 0; /* 关键:让按钮默认靠右 */ display: block; margin-left: auto; } article { width: 200%; }
HTML
<div> <input type="button" value="copy" /> <article> In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available. </article> </div>
原理说明
- 给按钮设置
display: block和margin-left: auto,让它默认在父容器的水平右侧位置,这是触发right: 0生效的前提。 - 当父容器水平滚动时,
position: sticky结合right: 0会让按钮固定在容器的右上角,垂直方向的top: 0依然保持原有效果。 - 该方案适配父容器宽高变化的场景,不需要硬编码宽度值。
内容的提问来源于stack exchange,提问作者Manas R. Makde
相关产品推荐
相关产品推荐

