Skip to content

Instantly share code, notes, and snippets.

@nilsel
Last active October 27, 2023 13:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nilsel/e28a40197c295bdc9d6e7851d3f68fe8 to your computer and use it in GitHub Desktop.
Web component to convert px to rem
/*
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