var num = 20; $('.class').css('transform', 'translateX(num * 2px)); 

How to make it so that a ready-made property is written to the class:

 transform: translateX(40px); 

    3 answers 3

     var num = 20; $('.class').css('transform', 'translateX(' + (num * 2) + 'px)'); 

      You could describe the transformation with something similar to 'transform', 'translateX(num * 2px)' if num * 2px were a function of css3, and only if the variable num declared directly in css.

      Because num is a javascript variable, then it, like the multiplication operator, must be separated by quotes:

       var num = 20; $('.class').css('transform', 'translateX(' + (num * 2) + 'px)'); 
       html { height: 100%; padding: 5px; } body { padding: 0px; margin: 0px; height: 100%; border: #ccc solid 1px; } * { box-sizing: border-box; } .class { width: 100px; height: 50px; background: #000; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="class"></div> 

      Option with css variables + calc() function

       $('.class').css('transform', 'translateX(calc(var(--num)*2))'); 
       :root { --num: 20px; } html { height: 100%; padding: 5px; } body { padding: 0px; margin: 0px; height: 100%; border: #ccc solid 1px; } * { box-sizing: border-box; } .class { width: 100px; height: 50px; background: #000; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="class"></div> 

      Browser support for css variables is here . Browser support for calc () is here .

         var num = 20; $('.class').css('transform', 'translateX('+(num * 2)+'px)'); 
         .class { width:50px; height:50px; background:#f1f1f1; box-shadow:0 0 10px rgba(0,0,0,0.5); } 
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="class"></div> 

        • And how does your answer differ from the previous 2x?) - Cheg
        • Anything, there is no other method better. A variant with --var crutches. - ishidex2