Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can `getBoundingClientRect` return values in `rem`?

I am using rems 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 rems? It would make my code a little simpler.

like image 760
brendangibson Avatar asked Oct 24 '25 09:10

brendangibson


1 Answers

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>
like image 131
Spectric Avatar answered Oct 25 '25 23:10

Spectric