Safari Viewport Bug, Issues with Fixed Position and Bottom or Top

后端 未结 1 617
我在风中等你
我在风中等你 2021-02-05 06:32

I\'m experiencing something strange in iOS 12.3.1 Safari. This issue dates back to at least iOS 12.2, but I imagine it\'s been a problem for much longer than th

相关标签:
1条回答
  • 2021-02-05 07:01

    Hello this question kind of got me at first and I thought back to my days poking around in HTML and CSS for hours on end trying to get things right. Alas all those hours of missery have been for this moment.

    vh used to be calculated by the current viewport of your browser. If you loaded a site in your browser, 1vh would be the same as 1% of your screen height, and then minus the browser interface.

    But! If you wanted to scroll, it gets tricky. Once you brush past the browser interface (in this case your address bar), you would have a wierd jump in your content because the vh would be updated.

    Safari for iOS was actually was one of the first to implement a fix. They set a fixed vh value based on the max screen height. Then the user wouldn't experience the jump in content, but .... yup, there's always a but...

    Having the fixed value is awesome, except when you wanna have a full sized element, or an element with fixed position at the bottom of the screen because then it would get cropped out!

    That is your problem....and say goodbye to it, because...

    This is your solution!!

    css:

    .my-element {
      height: 100vh; /* This is for browsers that don't support custom properties */
      height: calc(var(--vh, 1vh) * 100);
    }
    

    js:

    // Get the viewport height and multiply it by 1% to get a value for a vh unit
    let vh = window.innerHeight * 0.01;
    // Then set the custom --vh value to the root of the document
    document.documentElement.style.setProperty('--vh', `${vh}px`);
    

    Now you can use --vh as your height value like we would any other vh unit, multiply it by 100 and you have the full height we want.

    One thing left, the js up there runs, but we never update the element's size when the viewport changes, so that wouldn't work yet, you need a listener...

    more js:

    // We listen to the resize event
    window.addEventListener('resize', () => {
      // Update the element's size
      let vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    });
    

    Cheers!

    0 讨论(0)
提交回复
热议问题