17

After playing with position: sticky for a while, I started implementing it for sticky navigation and ran into this interesting, but frustrating scroll bouncing issue.

This is a common type of navigation behaviour seen on many sites, where you would traditionally use javascript to calculate offsets to a relative element in the page. When the element reaches the top of the window, a 'stuck' class would be added, taking the element out of the document flow with position: fixed, and a dummy element of the same height would be added in it's place to prevent the page from 'jumping'. Additionally, it's common to see javascript then shrink the height of that navigation to save space while scrolling.

CSS now seemingly takes care of all this with position: sticky, apart from (as far as I can tell), detecting when the element is 'stuck'. Instead I used some javascript to do the stuck detection, discovering that everything works great, right up until the height of the sticky element needs to change.

It's pretty hard to explain, but it wreaks havoc in production - so here's a stripped down example I've made to illustrate the issue as simply as possible.

CSS sticky position height adjustment bug

It's best illustrated when the height of the page is just the right length, so I've set a fixed height on the element to make sure everyone is able to see the same thing. You can add more content and it's still an issue when scrolling past.

The result is some really weird behaviour. When scrolling down, the navigation sticks, and as it shrinks the navbar, the 'dummy element' the browser is automatically creating courtesy of position: sticky seems to be kept in sync with it. That means, when the stuck class is added, the whole page gets smaller, and a fraction of a second later, the navigation is no longer stuck, thus resulting in a glitchy vibration loop.

The behaviour is also completely different across every browser I've tested. In chrome, this bouncing can never be resolved, it stays in the infinite loop constantly adding / removing the stuck class. More interestingly in Safari, the scroll position is 'pushed back' to a state where it wont bug out. Then in Firefox, it does both of these, glitching for a second or two, before forcing the scroll position back up again.

I'm wondering if anyone has experienced this, and come up with any solutions? Any js workaround I've come up with hasn't really worked or been very good! Surely as popularity grows, more people are going to hit this one...

Genius workarounds, hacks, insights, or perfect solutions all welcome!

bluefantail
  • 1,079
  • 1
  • 10
  • 14

5 Answers5

10

Try adding overflow-anchor: none; to the sticky element when applying changes that would alter its size (and potentially affect window size/element positioning).

Update: ultimately, the right solution I've hit on is: have an outer element that NEVER changes size (it's always the same full height at any given breakpoint). That one is made sticky. But it also should have no background/visual styles, and it's effective height should be defined by height + bottom margin (so that it takes up the right amount of initial space in the document, but doesn't actually block clicks once the visual nav shrinks and gives more space.

Then have an inner element that does change size, either in reality or just visually.

You can also use modern properties like contain: layout size; on the inner element like

Dtipson
  • 1,564
  • 16
  • 21
  • 1
    this is the only workaround that solves my problem with shrinking header on scroll ! ty – Benjamin Seche Mar 10 '20 at 09:22
  • Unfortunately this also isn't supported by Safari – osdiab Mar 18 '20 at 15:15
  • Yep. So far, the only solid solution I've found is giving the sticky header a fixed height and then resizing an internal part of it visually without changing the actual height of the outer sticky element. – Dtipson Mar 19 '20 at 14:17
  • Creating an outside container that does not shrink is a good idea but in my case it was causing the elements on the page to not be clickable when the invisible part of the sticky element was covering them. In case anybody else faces this problem, you can use the `pointer-events` CSS property. On the outer element, I set it as `pointer-events: none` and on the inner element whose size can change, I set it as `pointer-events: auto`. – xeraphin Mar 31 '23 at 08:04
2

(Apparently you need more reputation to comment than answer ...)

This seems like a legitimate layout bug, so I'm curious what the opinion of browser contributors might be. Raised issues in the Chromium and Firefox bug trackers to see what'll happen:

https://bugs.chromium.org/p/chromium/issues/detail?id=734461 https://bugzilla.mozilla.org/show_bug.cgi?id=1374171

Jono
  • 31
  • 1
2

I can confirm this is a problem after attempting the same thing. I'm using position sticky on my header and adding a class at the same time via JS (to trigger some animations which change height as the CodePen's above describe)

var header = document.getElementById("header");
var sticky = header.offsetTop;

window.onscroll = function () {
    if (window.scrollY > sticky) {
        header.classList.add("stuck");
    } else {
        header.classList.remove("stuck");
    }
};

The height change does in fact mess with the window height and as it becomes 1px smaller will trigger the else which removes my animation. Removing the animation changes the height back to the original size and the loop starts again.

I'd like to know how to code this correctly without a native stuck element/class/pseudo

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
2

This was driving me mad for a while, but (based on solution from This question/answer) a good solution is to create an additional external element that is the sticky one which never changes size, and then have the internal element change size/position within that container as needed.

An example fiddle I made with an observer to detect when 'stuck' (could also use scroll offset if there's just a fixed-size element above it):

https://jsfiddle.net/ccarnage/fveyc6nL/24/

Summary is:

<div id="sticky-container" style="height:100px;">
    <div id="header-contents-shrinkable">
     ...
    </div>
</div>

Where #header-contents-shrinkable will have its style changed when the sticky-container is stuck to the top of the page (e.g. height reduced)

ccarner
  • 566
  • 4
  • 6
1

I forked your pen.

Here is one workaround I came up with that visually gives the same effect.

It appears that transitioning a transform instead of height along with position: sticky works just fine. You don't get the constant class toggling.

So if we want to halve the height of our nav, we can squish it in half by changing scaleY from 1 to 0.5

This in turns squishes our links, so we then scale those up to double their original size to offset the squishing, adjusting scaleY from 1 to 2.

The last fix we have to do is translating the nav up to the top of the page to compensate for the smaller height.

Snippet is below. The key parts here are as follows:

nav {
  transform: scaleY(1) translateY(0);
}
nav a {
  transform: scaleY(1);
}
nav.stuck {
  transform: scaleY(0.5) translateY(-50%);
}
nav.stuck a {
  transform: scaleY(2);
}
nav, nav a {
  transition: all 0.6 ease-in-out;
}

The first two rules are not strictly necessary, but I like to include a before and after just to make things extra clear.

nav       = document.querySelector('nav');
section   = document.querySelector('section');

function supportSticky() {
  if(window.CSS && CSS.supports) {
    return CSS.supports("(position: sticky)") || CSS.supports("(position: -webkit-sticky)");
  } else {
    var el = document.createElement("div");
    el.style.position = "sticky";
    return el.style.position == "sticky";
  }
}

function handleScroll() {
  function isStuck(el) {
    return el.offsetTop - section.scrollTop <= 0 ? true : false;
  }

  isStuck(nav) ? nav.classList.add("stuck") : nav.classList.remove("stuck");
}

if (supportSticky()) section.addEventListener('scroll', handleScroll);
html,
body,
h1 {
  margin: 0;
  font-family: arial;
}

section {
  width: 100%;
  max-width: 600px;
  margin: 0px auto;
  box-shadow: 0 1px 7px #ccc;
  height: 378px;
  overflow-y: scroll;
}

header {
  padding: 3em;
}

nav {
  display: flex;
  width: 100%;
  background-color: #ddd;
  justify-content: center;
  padding: 3em;
  box-sizing: border-box;
  position: sticky;
  top: 0;
  transition: all .6s ease-in-out;
  transform: scaleY(1) translateY(0);
}
nav.stuck {
  background-color: red;
  transform: scaleY(0.5) translateY(-50%);
}
nav.stuck a {
  transform: scaleY(2);
}
nav a {
  text-decoration: none;
  color: #fff;
  padding: 1ch 1em;
  background-color: #bbb;
  margin-right: 1em;
  border-radius: 3px;
  transition: all .6s ease-in-out;
}
nav a:hover {
  background-color: #aaa;
}

article {
  padding: 3em;
}
<section>
  <header>
    <h1>CSS sticky position height adjustment bug</h1>
  </header>
  <nav>
    <a href="">Item 1</a>
    <a href="">Item 2</a>
    <a href="">Item 3</a>
    <a href="">Item 4</a>
  </nav>
  <article>
    <h1>Sticky navigation</h1>
    <p>The navigation above should shrink when it gets to the top.</p>
    
    <h1>There is no 'stuck feature' in CSS</h1>
    <p>So we need javascript to work that out, and set a stuck class.</p>
        
    <h1>But it bounces!</h1>
    <p>Because the dummy element is kept in sync with the nav height...</p>
  </article>
</section>
cjl750
  • 4,380
  • 3
  • 15
  • 27
  • Nice, that one didn't occur to me, thanks. This gets pretty chaotic outside the simple context of the example though. To have any control with a complex navigation structure would start to get pretty weird. The nav I'm using this on has tiles with quite specific spacing / padding that disappears completely when collapsed, and text in relative absolute positioned pseudo elements that need to move around to exact locations in the collapsed state. I guess you could use `calc()` or something to get some more control.. Also, if you use `transform-origin` here, the `translateY` isn't needed anymore. – bluefantail Jun 17 '17 at 08:13
  • 1
    Yeah, I figure whether this works or not depends on how complicated your real-life situation is. I am a big fan of complicated `calc()` expressions, but that may not save you still. It certainly is gonna probably end up being more CSS than what you would otherwise do just by toggling to `fixed` with some JavaScript. But on a simpler nav, you might be able to get away with something like `nav.stuck * { scaleY(2) }`. – cjl750 Jun 17 '17 at 21:39