I am using rem
s for my CSS sizes and am also using getBoundingClientRect
in javascript. getBoundingClientRect
returns it's values in px
by default. Is it possible to get it to return the values in rem
s? It would make my code a little simpler.
CodePudding user response:
You will have to convert it by dividing the pixels by the computed font size of the document:
function convertPixelsToRem(px) {
return px / parseFloat(getComputedStyle(document.documentElement).fontSize.replace('px', ''));
}
console.log(convertPixelsToRem(div.getBoundingClientRect().width))
#div{
width:100px;
height:100px;
background-color:grey;
margin-bottom:10px;
}
#div2{
width:6.25rem;
height:100px;
background-color:grey;
}
<div id="div"></div>
<div id="div2"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>