9

CSS Scroll Snap allows the browser to snap scroll to elements in a container. To apply the same logic to the vertical page scroll I found that it had to be applied to <body> rather than <html> (see below). This is not a major problem however it does effectively create a scrolling area out of <body> instead of using the window scroll.

Whilst this may seem fine it has a couple of side effects:

  • Window scroll functions can no longer be used in javascript
  • The rubber band effect on Apple browsers is less responsive and non existent in Chrome on Mac.

I wanted it to appear as native as possible therefore the only conclusion would be to apply it to <html> rather than <body>. Applying it this way however prevents it from functioning. If you apply it to both, it will render correctly in Safari but remains broken in Chrome and Firefox.

The issue is not because <body> creates a separation between the parent and child element as if another <div> is added in the hierarchy it will still function correctly.

Here is the functioning code but applied to <body> rather than <html>.

<html>
   <body>
      <div class="extra_parent">
         <div class="child">ONE</div>
         <div class="child">TWO</div>
         <div class="child">THREE etc..</div>
      </div>
   </body>
</html>

body {
    margin: 0;
    padding: 0;
    scroll-snap-type: y mandatory;
    overflow-y: scroll;
    height: 100vh;
}

html {
    height: 100vh;
    overflow: hidden
}

.child {
    position: relative;
    height: 80vh;
    font-size: 100px;
    text-align: center;
    line-height: 80vh;
    color: #000;
    scroll-snap-align: end;
}

Solve a Fiddle: https://jsfiddle.net/u8tsjven/

Alohci
  • 78,296
  • 16
  • 112
  • 156
Walrus
  • 19,801
  • 35
  • 121
  • 199
  • This codepen seems to do what you are looking for https://codepen.io/team/css-tricks/pen/yLLqqgP. Doesn't it? – a.barbieri Nov 26 '19 at 16:07
  • 1
    @a.barbieri - I think this is now working in FF, but still appears broken in Chrome for me. Chrome overscrolls after snapping and will skip to the next snap point if they are close together. – lawrence-witt Jul 27 '20 at 15:37

1 Answers1

1

You can make .extra_parent not interfere with scroll-snapping by adding the following rule:

.extra_parent {
  display: contents;
}

https://caniuse.com/css-display-contents

display: contents causes an element's children to appear as if they were direct children of the element's parent, ignoring the element itself.

Timo
  • 187
  • 1
  • 8
  • It's been a long time since I wrote in HTML and CSS but thank you for the answer. I'm not able to check it at this moment in time but it is appreciated. – Walrus Feb 24 '23 at 14:12
  • I understand . I in part answered it to keep StackOverflow somewhat uptodate and relevant (and `display: contents;` is a neat css rule). – Timo Apr 05 '23 at 07:38