Is it possible to apply CSS Scroll Snap to the HTML tag rather than the Body tag
Asked Answered
B

1

10

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/

Beaudry answered 27/2, 2019 at 10:19 Comment(2)
This codepen seems to do what you are looking for codepen.io/team/css-tricks/pen/yLLqqgP. Doesn't it? – Annice
@Annice - 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. – Removed
W
2

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.

Wiesbaden answered 24/2, 2023 at 14:8 Comment(2)
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. – Beaudry
I understand πŸ™‚. I in part answered it to keep StackOverflow somewhat uptodate and relevant πŸ˜‡ (and display: contents; is a neat css rule). – Wiesbaden

© 2022 - 2024 β€” McMap. All rights reserved.