固定 div 但在特定容器内

fixed div but inside a specific container

我想要一个侧边栏来排除页面上的任何滚动行为 - 所以它是 position:fixed

但我希望它作为父容器位于 wrap 内,而 right:0 来自 wrap 而不是来自 window。

如何操作?

.wrap{width:250px; margin:0 auto; height:100vh;background:silver;}
.sidebar{position:fixed;top:0;right:0;height:100vh;background:gold;}
<div class='wrap'>
<div class='sidebar'>sidebar</div>
</div>

一个想法是不定义 right 并告诉浏览器使用 static 位置。为此,您需要确保静态位置在右侧。

这是一个您必须调整方向(并为内容重新设置)的示例

.wrap {
  width: 250px;
  margin: 0 auto;
  height: 150vh;
  background: silver;
  direction:rtl;
}

.sidebar {
  position: fixed;
  top: 0;
  height: 100vh;
  background: gold;
}

.wrap > div:last-child {
  direction:ltr;
}

body {
 margin:0;
}
<div class='wrap'>
  <div class='sidebar'>sidebar</div>
  <div> some content</div>
</div>

来自the specification

For the purposes of this section and the next, the term "static position" (of an element) refers, roughly, to the position an element would have had in the normal flow.

然后

If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0. Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.


这是 position:sticky

的另一个想法

.wrap {
  width: 250px;
  margin: 0 auto;
  height: 150vh;
  background: silver;
}

.sidebar {
  position: sticky;
  float:right; /* Yes float!*/
  top: 0;
  height: 100vh;
  background: gold;
}


body {
 margin:0;
}
<div class='wrap'>
  <div class='sidebar'>sidebar</div>
  <div> some content</div>
</div>