身体{overflow-x:隐藏;中断位置:粘性 [英] body { overflow-x: hidden; } breaks position: sticky

查看:139
本文介绍了身体{overflow-x:隐藏;中断位置:粘性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要保持位置粘性的元素:

I have an element that I am making sticky with position sticky:

#header {
    position: sticky;
    width: 100vw;
    top: 0;
}

<app-header id="header"></app-header>

那很好,但是我意识到如果我使用:

And that works fine, but I realised that if I use:

body {
  overflow-x: hidden;
}

这会打破粘性,我需要将body overflow-x设置为hidden,如何仅使用CSS解决方案而不使用JS解决方案来解决此问题?

That breaks sticky, and I need to set body overflow-x to hidden, how can I fix that, with only CSS solution, no JS solutions?

推荐答案

更新:

已在Safari v12.0.2,Firefox v64.0和Chrome v71.0.3578.98上成功测试了

UPDATE:

This has been successfully tested on Safari v12.0.2, Firefox v64.0, and Chrome v71.0.3578.98

为Safari添加了position: -webkit-sticky;.

Added position: -webkit-sticky; for Safari.

不幸的是,规范对于overflow-x: hidden;对粘滞性的含义不太清楚,但是有一种方法可以解决此问题.幸运的是,有一个问题可以解决此问题: https://github.com/w3c/csswg -drafts/issues/865 .

Unfortunately the spec is not too clear about the implications of overflow-x: hidden; on position sticky, but there is a way to fix this. Thankfully there is an issue to hopefully fix this: https://github.com/w3c/csswg-drafts/issues/865.

简单解决方案是从要具有position: sticky;的元素的每个祖先中删除或取消设置overflow-x: hidden;.然后,您可以将overflow-x: hidden;放在身体上,它将起作用!

The simple solution is to remove or unset overflow-x: hidden; from every ancestor of the element you want to have position: sticky;. Then you can have overflow-x: hidden; on the body and it will work!

还要再次检查您是否在正文和html标签上都没有溢出,我在此处对此进行了更深入的介绍: https://stackoverflow.com/a/54116725/6502003

Also double check that you don't have overflow set on both the body and html tags which I posted about more in depth here: https://stackoverflow.com/a/54116725/6502003

如果您想使用它,这里是一支笔: https://codepen.io/RyanGarant/pen/REYPaJ

Here is a pen if you want to play around with it: https://codepen.io/RyanGarant/pen/REYPaJ

/* 
  Try commenting out overflow on body style and uncommenting
  overflow on .overflow-x-hidden class and you will see 
  position sticky stop working!  
*/

body {
  overflow-x: hidden;
}

.overflow-x-hidden {
/*   overflow-x: hidden; */
  border: 1px solid blue;
}

h1 {
  background: palevioletred;
  color: #fff;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.tall {
  background: linear-gradient(to bottom, paleturquoise, white);
  height: 300vh;
  width: 100%;
}

<div class="overflow-x-hidden">
  <h1>I want to be sticky!</h1>
  
  <div class="tall"></div>
</div>

这篇关于身体{overflow-x:隐藏;中断位置:粘性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆