Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

379
Views
Setting element.style.left using calc() in JavaScript does not work when calculations are involved

I have the following code:

<div id="container"></div>

and in my JavaScript code, I am trying to set its left property value to the result of a calculation. This same calculation works in CSS but not when used in JavaScript code.

var element = document.getElementById("container");

element.style.left = "calc(" + (container.clientWidth + containerUnit + " / 2 - " + child.clientWidth + unit + " / 2") + ");";

But, console.log(element.style.left) returns: (blank value here). And upon setting this style in JS, no effect is made on the element.

containerUnint contains "px" and unit contains "%"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is that you're passing an invalid value to calc(), so the browser is not applying it. You have to specify measurements for CSS to understand how to actually execute the calculation.

Your current concatenation compiles to something like:

calc(200 / 2 - 10 / 2);

I guess you're working in pixels, so you need to update your definition as follows:

element.style.left = "calc(" + (container.clientWidth + containerUnit + "px / 2 - " + child.clientWidth + unit + "px / 2") + ")";

Notice that you should also lose the trailing ;:

const element = document.getElementById("container");

const containerUnit = '%';
const unit = 'px';

element.style.left = "calc(" + (10 + containerUnit + " / 2 - " + 10 + unit + " / 2") + ")";

console.log(element.style.left)
<div id="container"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!