Safari位置:粘性在overflow:auto元素中不起作用
根据 CanIUse ,
According to CanIUse, there is a known issue with Safari and position:sticky
inside an overflow:auto
element:
将父级设置为自动溢出会阻止位置:粘性在Safari中工作
A parent with overflow set to auto will prevent position: sticky from working in Safari
但是,这是我需要的确切用例.我有一个可滚动的div,它分为两列.即使滚动整个div,右边的列也应该是粘性的,并且永远不要动.我在右列上使用position:sticky
的原因是我希望用户仍然能够使用光标在右列上滚动左列.这是我发现可行的唯一解决方案.
However, this is the exact use case that I need. I have a scrollable div, which is subdivided into two columns. The right column should be sticky and never move, even when the entire div is scrolled. The reason I'm using position:sticky
on the right column is that I want the user to be able to still scroll the left column with the cursor on the right column. And this was the only solution that I found to have worked.
此处是Firefox/Chrome的工作示例: http://cssdeck.com/labs/zfiuz4pc 滚动时,橙色区域保持固定,但在Safari中不是.
A working example for Firefox / Chrome is here: http://cssdeck.com/labs/zfiuz4pc The orange area remains fixed while scrolling, but in Safari it doesn't.
上面的示例对我的问题有一些不必要的包装,但是我想尽可能地复制要在其中运行此代码的环境.其基本要点是:
The example above has some unnecessary wrappers to my issue, but I wanted to replicate as closely as possible the environment where I want to have this code working in. The basic gist of it is I have this:
<div class="modal-content">
<div class="left-content">
</div>
<div class="sticky-element">
</div>
</div>
和CSS:
.modal-content {
display: flex;
overflow: auto;
flex-flow: row nowrap;
}
.left-content {
flex: 0 0 300px;
}
.sticky-element {
position: sticky;
top: 0;
right: 0;
width: 200px;
}
同样,这在FF/Chrome中有效,但在Safari中无效.有没有变通办法可以使其在所有浏览器中都能正常工作?还是有一种我可以用来保持滚动性的方法,即使将鼠标指针移到粘性元素上也可以保持滚动性吗?
Again, this works in FF/Chrome but not in Safari. Is there a workaround to get it to work in all browsers? Or is there a different approach I can use to maintain scrollability even with the mouse cursor over the sticky element?
我从别人那里得到了这个解决方案:
I got this solution from someone else:
http://cssdeck.com/labs/bu0nx69w
基本上,而不是position:sticky
,请在右侧面板中使用position:fixed
.关键还在于您在父div中(在上面的示例中,在.modal-content
中)will-change:transform
,以便position:fixed
相对于该父而不是视口变得固定.这是一个整洁的小把戏
Basically, instead of position:sticky
, use position:fixed
for the right panel. The key is to also you will-change:transform
in a parent div (in the above example, in .modal-content
) so position:fixed
becomes fixed relative to that parent, and not the viewport. It's a neat little trick