container scrolls to top when children element hei

2020-02-29 11:25发布

问题:

I came across a bit quirky behavior. At least it seems quirky to me.

You can check it out here: https://fiddle.jshell.net/mxmcd9Lw/8/show/

Mainly when a element's height changes its parent element scrolls automatically to the top (you need to scroll down a bit first). Seems like offset top is lost because of the repaint that is caused by a height change.

  • structure is based on CSS Grid
  • body overflow is set to hidden
  • main container .l-page is set to 100vh
  • scrolled container .l-content

 body {
  overflow-y: hidden;
}

.l-page {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-template-rows: auto auto auto 1fr;
  grid-template-areas: 'primary_bar primary_bar' 'sidebar notification' 'sidebar secondary_bar' 'sidebar content';
  width: 100vw;
  height: 100vh;
  margin: 0 auto;
  min-width: 1280px;
  max-width: 1920px;
}

.l-notification {
  grid-area: notification;
}

.l-primary-bar {
  grid-area: primary_bar;
  z-index: 2;
}

.l-secondary-bar {
  grid-area: secondary_bar;
  z-index: 1;
}

.l-sidebar {
  grid-area: sidebar;
  width: 180px;
}

.l-content {
  grid-area: content;
  overflow-x: hidden;
  z-index: 0;
}

I tried:

  • setting both html and body to overflow hidden
  • setting both html and body height, min-height to 100% in different configuration
  • https://abdus.co/blog/preventing-vh-jump-on-mobile-browsers/ (method 2)

but with no luck.

I am sure it has something to do with the fact that body is not scrollable and that main container's height is set to 100vh.

Note On Chrome it jumps to the very top, on FF and Safari to the bottom.

Any help will be highly appreciated.

Thx!

Lukas

回答1:

This seems to happen most times when the grid-area is set to something dynamic and has overflow - for example if you set .l-page to grid-template-rows: repeat(4, auto) the bug is still present, but in grid-template-rows: repeat(4, 100px) it is not.

I have found a work-around that works in Chrome. Setting .l-page to grid-template-rows: auto auto auto minmax(1px, 1fr); somehow keeps the scroll position as you would expect. I don't know why though.

Here's the modified fiddle: https://fiddle.jshell.net/mxmcd9Lw/59/

Also, worth noting in Firefox Developer Edition v60 the bug appears to be fixed - your example works fine there. So I assume this is a known bug that will be resolved by browsers shortly.