如何将元素浮动到可能存在的右侧滚动条旁边?

3
我希望无论页面是否出现滚动条,我的页面元素都能保持在相同位置。我已经成功实现了主要内容的这一点,通过将 body 设为100vw,给主要内容设置一个等于滚动条宽度的 margin-right (假设滚动条宽度固定为 16px)。但是我无法弄清如何让右侧内容停留在滚动条左边缘的位置。
在下面的示例中,“Right”文本应该在出现滚动条时不改变位置,并且其所有文本应该保持可见,而不需要硬编码它的left(因为每次其内容宽度更改时都必须更改) 。

const { style } = main;
setInterval(() => {
  // simulating lots of main content
  style.height = style.height ? '' : '1000px';
}, 2000);
body {
  margin-top: 40px; /* because the "Result" gets in the way */
  width: 100vw;
  margin: 0;
}
#right {
  position: absolute;
  right: 0;
}
#right > div {
  margin-right: 16px; /* SCROLLBAR WIDTH */
}

#main {
  padding-top: 60px;
  margin-right: 16px; /* SCROLLBAR WIDTH */
}
#main > div {
  text-align: center;
  margin: 0;
}
<div id=right>
  <div>
    Right
  </div>
</div>
<div id=main>
  <div>
    Main content (does not change position)
  </div>
</div>

我尝试了很多float: rightposition: absolutemargin-rightright属性的组合,以及在右侧嵌套另一个容器,但没有达到所需的效果。如何实现?

1个回答

3
使用左对齐而非右对齐与vw单位一起使用,并通过翻译进行校正。

const { style } = main;
setInterval(() => {
  // simulating lots of main content
  style.height = style.height ? '' : '1000px';
}, 2000);
body {
  margin-top: 40px; /* because the "Result" gets in the way */
  width: 100vw;
  margin: 0;
}
#right {
  position: absolute;
  left: 100vw; /* all the way to the left */
  transform:translateX(calc(-1*(100% + 16px))); /* move back considering 100% of its width and scrollbar width*/
}
#right > div {
  margin-right: 16px; /* SCROLLBAR WIDTH */
}

#main {
  padding-top: 60px;
  margin-right: 16px; /* SCROLLBAR WIDTH */
}
#main > div {
  text-align: center;
  margin: 0;
}
<div id=right>
  <div>
    Right
  </div>
</div>
<div id=main>
  <div>
    Main content (does not change position)
  </div>
</div>


有趣。似乎需要指定“left”,然后进行转换才能将其移回,但它确实有效,我很感激。 - Snow
@Snow 看起来这是唯一避免滚动效果的方法。你需要考虑左侧参考而不是右侧参考。 - Temani Afif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接