Created
June 12, 2025 13:16
-
-
Save Velunce/9a7bf29f7f113088d306c129da5763c4 to your computer and use it in GitHub Desktop.
This JavaScript snippet dynamically adjusts the font size of the body and sets the rem unit based on the viewport width. It ensures that the font size is responsive and adapts to different screen sizes, enhancing readability on mobile devices. The script also detects support for 0.5px borders for better styling on high-DPI displays.
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
| (function flexible (window, document) { | |
| var docEl = document.documentElement | |
| var dpr = window.devicePixelRatio || 1 | |
| // adjust body font size | |
| function setBodyFontSize () { | |
| if (document.body) { | |
| document.body.style.fontSize = (12 * dpr) + 'px' | |
| } | |
| else { | |
| document.addEventListener('DOMContentLoaded', setBodyFontSize) | |
| } | |
| } | |
| setBodyFontSize(); | |
| // set 1rem = viewWidth / 10 | |
| function setRemUnit () { | |
| var rem = docEl.clientWidth / 10 | |
| docEl.style.fontSize = rem + 'px' | |
| } | |
| setRemUnit() | |
| // reset rem unit on page resize | |
| window.addEventListener('resize', setRemUnit) | |
| window.addEventListener('pageshow', function (e) { | |
| if (e.persisted) { | |
| setRemUnit() | |
| } | |
| }) | |
| // detect 0.5px supports | |
| if (dpr >= 2) { | |
| var fakeBody = document.createElement('body') | |
| var testElement = document.createElement('div') | |
| testElement.style.border = '.5px solid transparent' | |
| fakeBody.appendChild(testElement) | |
| docEl.appendChild(fakeBody) | |
| if (testElement.offsetHeight === 1) { | |
| docEl.classList.add('hairlines') | |
| } | |
| docEl.removeChild(fakeBody) | |
| } | |
| }(window, document)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment