Home >Web Front-end >CSS Tutorial >How to Achieve a Fixed Position in Mobile Safari?
Fixing Positions in Mobile Safari
Positioning an element fixed relative to the viewport in Mobile Safari has been a longstanding challenge. The traditional method of using position: fixed often fails in this browser.
Alternative Solution
Gmail recently introduced an innovative solution that offers an approximation of a fixed position. The trick lies in dynamically adjusting the top position of the element on scroll.
JavaScript Implementation
This alternative method can be implemented with just a few lines of JavaScript:
window.onscroll = function() { document.getElementById('fixedDiv').style.top = (window.pageYOffset + window.innerHeight - 25) + 'px'; };
In this code, the onscroll event listener updates the top CSS property of the element with the id="fixedDiv". The formula used ensures that the element is always positioned at the bottom of the viewport, with a small offset of 25 pixels.
By constantly adjusting the element's position on scroll, this code effectively simulates a fixed position that remains anchored to the viewport in Mobile Safari.
The above is the detailed content of How to Achieve a Fixed Position in Mobile Safari?. For more information, please follow other related articles on the PHP Chinese website!