Problems converting px to Percentage

2

I have this code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div style="width:50%;height:30%;background:#65C6BB;position:absolute;transform: translate(20px,0px);">
    </div>
    
  </body>
</html>

I wanted to convert the 'transform' CSS property to percentage as well.

I'm using the rule: (100 / window.innerWidth) *pixels

Just doing this my result for a 1920 Window Width is: 1.0416666666666667 ...

If I replace this in the CSS property 'transform' like this:

transform: translate(1.0416666666666667%,0px);

The div will not stay in the same position. I have tried using window.document.body.offsetWidth but it also does not work.

Does anyone know what the solution is?

    
asked by anonymous 15.03.2016 / 15:18

1 answer

1

Transform using% moves the element relative to the size of the element and not the size of its parent. So the formula should be

(100 / element.offsetWidth) * pixels

Source: link

    
21.03.2016 / 17:27