Home > Web Front-end > CSS Tutorial > How to Achieve a Fixed Position in Mobile Safari?

How to Achieve a Fixed Position in Mobile Safari?

Susan Sarandon
Release: 2024-11-20 18:35:22
Original
999 people have browsed it

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';
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template