-
Notifications
You must be signed in to change notification settings - Fork 734
Description
Imagine an environment variable that returns the current page zoom level for the web page in the (desktop) browser. The value would be a number (1 = 100%).
env(page-zoom-level)
My use case:
I have a chart that is very wide, so the web page that contains this chart scrolls horizontally instead of vertically.
On initial page load (at 100% page zoom), I want the chart to be full height (the full viewport height).
If the user changes the page zoom level, I want my chart to change size accordingly.
If the user changes the page zoom level and then navigates away to a different website and later returns to my page, the web browser will retain the page zoom level that the user set on the first visit to my website, so I want my chart to be sized accordingly (not full height).
This is difficult to implement. I made it work in Chrome and Firefox by storing the initial devicePixelRatio
in localStorage
, and then computing the DPR ratio (current DPR / initial DPR):
// store DPR once on the very first visit (under the assumption
// that the page zoom level is 100%)
if (!localStorage.getItem('DPR')) {
localStorage.setItem('DPR', window.devicePixelRatio);
}
let update = () => {
let dpr0 = localStorage.getItem('DPR');
let dpr = window.devicePixelRatio;
let zoom = dpr / dpr0;
// the height of my chart adjusted for page zoom
let height = zoom * window.innerHeight;
setChartHeight(height);
};
// update chart height on page load and window resize
update();
window.addEventListener('resize', update);
You can see it in action at https://switch2.šime.eu (change page zoom level, navigate away and back, optionally resize browser window)
This method does not work correctly in Safari because that browser does not update devicePixelRatio
on page zoom. I could make it work with a different algorithm (e.g. comparing changes to innerWidth
and innerHeight
), but it’s difficult to make such code reliable. A CSS environment variable that just tells me the current page zoom level would really help me out:
#content {
/* initially full height but changes with page zoom */
height: calc(env(page-zoom-level) * 100svh);
}
The crux of my problem is that I want my content to be full height (100svh
) at page zoom level 100%, but if the user changes the page zoom level, I want my content height to change accordingly (relative to the viewport). So 100svh
only at page zoom 100%. A version of 100svh
that is affected by page zoom.
To me, this does not seem like an unusual thing to want. For some types of content (like my chart that scrolls horizontally), having the content automatically be full height on initial page load provides a better UX, but at the same time page zoom is an accessibility feature that websites should support, so I think my use-case is valid.