Last active
June 11, 2021 20:55
-
-
Save trvswgnr/6f2604e7da204292ef9ae5f617478045 to your computer and use it in GitHub Desktop.
Change "vh" and "vh" to account for browser top and bottom bars
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Update CSS variables --vh and --vh to be accurate taking mobile browser address and bottom action bars into consideration. | |
| * | |
| * @author Travis Aaron Wagner <travis@travisawagner.com> | |
| */ | |
| let wHSaved = Math.min(window.innerHeight, window.outerHeight); | |
| let wWSaved = Math.min(window.innerWidth, window.outerWidth); | |
| /** | |
| * Updates the "--vh" and "--vw" CSS variables if there is a large enough change in window size | |
| * | |
| * @param {number} [tolerance=120] How big of a window size change needs to occur to trigger the adjustment. | |
| * @param {boolean} [force=false] Whether to force the change. | |
| * @returns {boolean} Whether there was a large enough change in window size to adjust variables. | |
| */ | |
| const updateVhVwCssVars = (tolerance = 120, force = false) => { | |
| const wH = Math.min(window.innerHeight, window.outerHeight); | |
| const wW = Math.min(window.innerWidth, window.outerWidth); | |
| let toleranceExceeded = false; | |
| if (!wHSaved || Math.abs(wHSaved - wH) > tolerance) { | |
| wHSaved = wH; | |
| toleranceExceeded = true; | |
| } | |
| if (!wWSaved || Math.abs(wWSaved - wW) > tolerance) { | |
| wWSaved = wW; | |
| toleranceExceeded = true; | |
| } | |
| if (!toleranceExceeded && !force) { | |
| return toleranceExceeded; | |
| } | |
| // update the css variables | |
| document.documentElement.style.setProperty('--vh', `${wHSaved/100}px`); | |
| document.documentElement.style.setProperty('--vw', `${wWSaved/100}px`); | |
| return toleranceExceeded; | |
| }; | |
| const windowResized = (e) => { | |
| const force = e.type === 'DOMContentLoaded'; | |
| updateVhVwCssVars(120, force); | |
| }; | |
| window.addEventListener('resize', windowResized); | |
| document.addEventListener('DOMContentLoaded', windowResized); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| :root { | |
| --vh: 1vh; | |
| --vw: 1vw; | |
| } | |
| @function vh($num) { | |
| @return calc(var(--vh) * #{$num}); | |
| } | |
| @function vw($num) { | |
| @return calc(var(--vw) * #{$num}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment