How CSS Position Sticky Really Works: Tips For Beginners.

If you just started learning HTML/CSS, you can easily get caught by the outstanding improvements that we get every day, like flexbox or grid... or a framework why not.

But, even if you learned how to put 1 or 2 rules and already using bootstrap, to name a popular one is good to know how things work.

Today, taking my daily walk down memory lane, I remembered the first HTML task I built using... bootstrap and how, in my precarious knowledge, position sticky saved me.

I will not stop on position static, relative, fixed, and absolute. For this article's purpose, it will be harder for me not to make myself a rabbit hole and start talking too much about stacking context (still worth a small appearance), among other concepts that entirely make these rules, and in the end, defines how everything looks.

Position Sticky This position will mutate between relative and fixed properties, considering where your viewport is right now.

.sticky {
  position: sticky;
  top: 50px;
}

When you apply sticky, two things are happening. The normal flow of the document slightly changes since now this element will not be static, and therefore new rules like the one you see top:50px; can be applied and tell the DOM where or when to render it.

The intriguing part of sticky is that "mutate between relative and fixed." That is pretty much what is doing. When you start scrolling and to get to that 50px. The element will switch to fixed right in that place.

Now I encourage you to go to the fiddle and add position: relative; to the empty .relative class.

What you will see in any case is the text suddenly overlapping the navbar.

Z-index index ft. Stacking Context

Sometimes because of this, these kinds of problems appear, and you can patch it with Z-index.

Stacking Context, is the three-dimensional conceptualization of HTML that it traduces to "What will it render first?". If things are position in the same place, whatever is rendering last is what you will see. And this goes hand in hand with Z-index in the case that you don't know, will let you position your element on this conceptualization. The stacking context will usually change every time you are not using a "static element" in one or another way.

Having this little crumble of knowledge, we can deduce that this happens with position relative, and that is why we are having a problem.

/* Cheap / Quick solution */

.z-index { 
/* To"go up" */
z-index: 100; 
/* To "go down" */
 z-index: -100;
}

To conclude

If you are a beginner with programming, it may be daunting to read the official documentation for answers but, if the documentation is good enough, you'll have everything you need.

These will not be the case for every documentation you read. I had awful experiences. This one is not the case.