Last active
October 27, 2023 13:40
-
-
Save nilsel/e28a40197c295bdc9d6e7851d3f68fe8 to your computer and use it in GitHub Desktop.
Web component to convert px to rem
This file contains 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
/* | |
Quick and dirty web component to convert px to rem | |
Base font size is set to 16px (browser default) | |
Usage: | |
<px-to-rem px="32/48"/> | |
Returns: | |
32/48px - 2/3rem | |
*/ | |
class PxToRem extends HTMLElement { | |
static define(tagName = 'px-to-rem') { | |
customElements.define(tagName, this) | |
} | |
get px() { | |
const px = this.getAttribute('px') | |
if (!px) { | |
console.log('px attribute missing') | |
return ''; | |
} | |
return px.split('/'); | |
} | |
calculateRem(px) { | |
const rems = []; | |
px.forEach(val => { | |
rems.push(val / 16); | |
}); | |
return rems.join('/'); | |
} | |
connectedCallback() { | |
this.textContent = | |
`${this.px.join('/')}px - | |
${this.calculateRem(this.px)}rem`; | |
} | |
} | |
PxToRem.define(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment