Search code examples
htmlcsszooming

How to keep the zoom level uniform between multiple HTML pages?


I have multiple html webpages that follow the same layout. By that I mean that they all have the same banner with the website name on the top, a navigation bar below that (with the same links), etc. . My problem is when a user visits the website and manually zooms (by holding CTRL + Mousewheel) and then visits a link that links to another webpage with the same layout, the zoom level gets reset to the default one. For example if I just zoom in by 5 % more than the default zoom was and visit a link, the zoom resets by -5 % to the default one.

How do I keep a uniform zoom level between the pages home.html -> a.html and b.html, so that, whereever the user zooms and switches the links, it stays the same way on the other pages? Do I need Javascipt for that or can I do that with a CSS command?


Solution

  • There is definitely no way to detect, let alone set browser zooming with CSS.

    There is one super impractical way to roughly imitate browser zoom. You'd have to wrap your document in a container, and then change the value of the container's transform: scale() or the zoom property, but I'd suggest not even trying to attempt this since it would likely be extremely unreliable. Here is an SO question and answer discussing the transform: scale() and zoom.

    You could also explore this, which would likely be a bit more reliable, but still impractical.

    There is also no way, I believe, to set the native zoom level of a browser even with JS.

    However, you can at least detect the level of zoom, but only in newer browsers. In newer browsers, browser zooming will trigger a window.onresize event.

    In Chrome 74 and Firefox 66, you can retrieve the zoom value with the following code.

    window.onresize = function(e){
      console.log(e.currentTarget.devicePixelRatio)
      // 0.5 is equal to 50%
      // 1 to 100%
      // 2 to 200%
      // so on and so forth
    }
    

    Regarding mobile, on iOS 10 you can add an event listener to the touchmove event to detect if the page is zoomed with the current event, according to this answer from 2016; I'm sure more progress has been made since then.

    Anyways, best of luck.