【问题标题】:fixed div but inside a specific container固定 div 但在特定容器内
【发布时间】:2019-06-29 20:19:37
【问题描述】:

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

但我希望它在 wrap 中作为父容器,right:0 来自 wrap 而不是来自窗口。

如何做到这一点?

.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>

【问题讨论】:

  • position:sticky 代替?
  • @TemaniAfif,很粘...我不确定,请举个例子

标签: html css fixed


【解决方案1】:

一个想法是不定义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

就本节和下节而言,术语“静态位置”(元素的)大致指的是元素在正常流程中的位置。

然后

如果'left'、'width'和'right'这三个都是'auto':首先将'margin-left'和'margin-right'的任何'auto'值设置为0。然后,如果建立包含静态位置的块的元素的“方向”属性是“ltr”,将“左”设置为静态位置并应用下面的规则三;否则,将“right”设置为静态位置并应用下面的第一条规则。


这是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>

【讨论】:

  • 巧妙使用dir
  • 我真的必须说——为什么position:fixed-in-parent——例如——不存在?
  • @qadenza 确实如此,它被称为sticky,但在这种情况下这将是诡计..也会添加答案
猜你喜欢
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 2011-02-20
  • 2017-07-28
  • 2018-12-12
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多