我希望我的页面元素保持在相同的位置,而不管右边缘是否有滚动条。 我已经设法为主要内容实现了这一点,方法是为主体提供100vw
,并为主要内容提供滚动条宽度的Margin-Right
。 (为了简单起见,假设滚动条的宽度固定为16px.) 但是我不知道如何使右边的内容坚持到滚动条左边的位置。
在下面的示例中,当滚动条出现时,“右”文本不应该改变位置,并且它的所有文本都应该保持可见,而无需对其left
进行硬编码(因为每次改变其内容宽度时,都必须对其进行硬编码)。
null
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>
null
我在元素上尝试了许多float:right
,position:absolute
,margin-right
和right
属性的组合,并尝试在右侧嵌套另一个容器,但没有得到我想要的结果。 如何才能做到这一点呢?
使用vw
单元的“左”而不是“右”,并使用翻译进行校正:
null
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>