首页 > 解决方案 > 如何在特定元素内放置固定按钮

问题描述

我需要一个按钮story在单击时滚动到顶部。
但我需要它在里面story,而不是外面。
此外,它不能滚动,所以定位固定。
但如果是fixed- 如何将它放在里面story,即距离右边界 14 px story

.story{
position:relative;
width:50%;
margin:0 auto;
height:100vh;
background:#ddd;
overflow-y:scroll;
}

.gotop{
position:fixed;
right:14px;
bottom:0;
padding:14px 9px;
background:gold;
border-radius:45% 45% 0 0;
cursor:pointer;
}
<div class='story'>
<div class='gotop'>TOP</div>
</div>

标签: htmlcss

解决方案


position: sticky和对你的标记的小改动可能会起作用。

如果您设置.gotop为粘性并将其加载到故事的最底部。然后,您可以使用强制将其卡在底部bottom: 0

我用float这里把它推到右边,这很丑。如果你使用 flex,你可以摆脱它,但我不知道你的其余标记。

.story {
  position: relative;
  width: 50%;
  margin: 0 auto;
  height: 70vh;
  background: #ddd;
  overflow-y: auto;
}

.gotop {
  position: -webkit-sticky;
  position: sticky;
  float: right;
  margin-right: 10px;
  bottom: 0;
  padding: 14px 9px;
  background: gold;
  border-radius: 45% 45% 0 0;
  cursor: pointer;
}
<div class='story'>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <p>Example</p>
  <div class='gotop'>TOP</div>
</div>


推荐阅读