【问题标题】:Sticky element in a nested child嵌套子项中的粘性元素
【发布时间】:2021-11-25 15:09:13
【问题描述】:

我有以下 html,包含一个可滚动的 div 和一个子行列表。 行的大小大于容器的宽度,因此滚动条是可见的。

每一行都有一个宽度等于最顶部 div 的单元格,以及一个在非滚动视图中不可见的第二个单元格。向右滚动,我们可以看到它。

我想要实现的是利用 css 的粘性位置,使粘性单元始终可见。

<div id="scrollable-container" style="background-color: lightgrey; height: 150px; width: 600px; overflow: auto;">
    <div id="fit" style="height: 150px; width: 800px;">
        <div id="row" style="height: 100px; width: 800px; display: flex;">
            <div id="cell" style="background-color: yellow; height: 100px; width: 600px;"></div>
            <div id="cell-sticky"
                 style="background-color: red; height: 100px; width: 100px; position: sticky; left: 0px;"></div>
        </div>
    </div>
</div>

有人可以解释为什么这个单元格粘性 div 不可见吗?有没有办法实现这个功能?

【问题讨论】:

  • 我试过你的代码,对我来说它是可见的。我需要向右滚动。之所以在右边是因为你在父div上使用了display: flex
  • 如前所述,我想利用粘性位置始终显示 div
  • 你总是会在正确的位置显示 div 吗?如果是,则设置正确:0
  • 我认为您使用的术语存在误解。当您的意思是“始终显示”时,您的意思是您可能总是希望 div 位于左侧?
  • 我会改写我的问题以更清楚

标签: html css sticky


【解决方案1】:

基于此,我将粘性位置切换为 right: 0px 而不是 left: 0px

粘性定位元素是计算位置的元素 价值是粘性的。它被视为相对定位,直到它 包含块超过指定阈值(例如将顶部设置为 其流根(或它的容器)内的值而不是 auto 内滚动),此时它被视为“卡住”直到相遇 其包含块的对边。

还有这个……

请注意,粘性元素“粘”到其最近的祖先,该祖先具有 “滚动机制”(在隐藏溢出时创建,滚动,自动, 或覆盖),即使该祖先实际上不是最近的 滚动的祖先。这有效地抑制了任何“粘性”行为 (请参阅 W3C CSSWG 上的 GitHub 问题)。 MDN

这会使粘性 div 保持在视图中,并且仅在水平上下文中粘在最近的可滚动元素(在本例中为最外层 div)的右边缘,直到遇到其包含块的相对边缘(具有 id 的 div '行')。

<div id="scrollable-container" style="background-color: lightgrey; height: 150px; width: 600px; overflow: auto;">
    <div id="fit" style="height: 150px; width: 800px;">
        <div id="row" style="height: 100px; width: 800px; display: flex;">
            <div id="cell" style="background-color: yellow; height: 100px; width: 600px;">The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:</div>
            <div id="cell-sticky"
                 style="background-color: red; height: 100px; width: 100px; position: sticky; right: 0px;"></div>
        </div>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多