Sticky Element Needs Siblings

Apparently, a sticky element requires siblings to stick to.

Can’t sticky elements simply act as if their container is fixed, and their position is relative to the container, once the sticky position requirements are met?

I don’t understand why siblings have to exist.

There are multiple ways to achieve the same goal.

Why do you believe that to be true? The only requirements I know of are container (ancestor) requirements, not siblings.


Example code:

Single element (only has ancestors)

<nav></nav>

Sticky the nav

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  height: 2000px;
}

nav {
  position: sticky;
  top: 0;
  left: 0;
  height: 70px;
  background-color: orange;
}
1 Like

Source I’m coming from:

It would help if they gave an actual example instead of just saying “When I added more elements inside the wrapper element, it started working.” because just adding another sibling element to the code given is not going to do anything. I also do not understand the explanation they give and there are multiple people in the comments commenting on this part of the article as well.

The sticky position element needs a scroll container (nearest scrollport) if the wrapper is meant to be that it has to have a scroll overflow. If adding extra child elements (i.e. siblings) was to create an overflow and the wrapper had a fixed height and an overflow set to one of the values that will create a scroll container, then yes the extra siblings would create the needed overflow. But that is not what the author is suggesting.

Note that a sticky element “sticks” to its nearest ancestor that has a “scrolling mechanism” (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn’t the nearest actually scrolling ancestor.

Example, sticks to the wrapper, not the body.

<div class="wrapper">
  <div class="sticky">
    SOME CONTENT
  </div>
  <p>test</p>
  <p>test</p>
  <p>test</p>
  <p>test</p>
  <p>test</p>
  <p>test</p>
</div>
body {
  height: 2000px;
}

.wrapper {
  height: 100px;
  overflow-y: scroll;
}

.sticky {
  position: sticky;
  top: 0;
}

I can find no mention of siblings in the specs.

https://drafts.csswg.org/css-position/#stickypos-insets

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.