Positioning with position: sticky

Viewed 85

Codepen reproducing this issue.

I am working on a personal project, but ran into a weird problem. As you can see blow I have 3 sections, which are supposed to be layed out after each other. Due to the nature of position: sticky, I want them to stick to the top after scrolling them. They have however a weird offset and only the third section sticks to the top after scrolling.

//
$enable-sticky-sections: true;

$sticky-section-count: 3;
//

*,
::after,
::before {
  box-sizing: border-box;
}

html {
  font-family: -apple-system, BlinkMacSystemFont,
    "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans",
    "Droid Sans", "Helvetica Neue", sans-serif;
  font-size: 1rem;
  line-height: 1.5;
}

body {
  margin: 0;
}

body {
  > {
    section {
      position: relative;
    }
  }
}

@if($enable-sticky-sections) {
  body {
    > {
      section {
        position: sticky;
        min-height: 100vh;

        @for $i from 1 through $sticky-section-count - 1 {
          &:nth-of-type(#{$i + 1}) {
            top: calc(#{100 * $i}vh - #{20 * $i}px);
            z-index: #{100 * $i};
            //
            background-color: #{#2196f3 * $i};
            //
          }
        }
      }
    }
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="src/css/page.css">
</head>
<body>
  <section></section>
  <section></section>
  <section></section>
</body>
</html>

1 Answers

I forgot that position: sticky works like position: relative until its scrolled through. Meaning instead of top: calc(#{100 * $i}vh - #{20 * $i}px);, I need to go: margin-top: -#{20 * $i}px;.

Here is a working example

//
$enable-sticky-sections: true;

$sticky-section-count: 3;
//

*,
::after,
::before {
  box-sizing: border-box;
}

html {
  font-family: -apple-system, BlinkMacSystemFont,
    "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans",
    "Droid Sans", "Helvetica Neue", sans-serif;
  font-size: 1rem;
  line-height: 1.5;
}

body {
  margin: 0;
}

body {
  > {
    section {
      position: relative;
    }
  }
}

@if($enable-sticky-sections) {
  body {
    > {
      section {
        position: sticky;
        min-height: 100vh;

        @for $i from 1 through $sticky-section-count - 1 {
          &:nth-of-type(#{$i + 1}) {
            margin-top: -#{20 * $i}px;
            z-index: #{100 * $i};
            //
            background-color: #{#2196f3 * $i};
            //
          }
        }
      }
    }
  }
}
<section></section>
<section></section>
<section></section>

Related