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

238
Views
Can I prevent calc() from simplifying when setting the style in Javascript?

I created a function in JavaScript to apply a style.right to an element. Depending on the media width, I am applying one of the following three styles to it

listElements[i].style.right = "calc(425 * " + portfolioScrollPosition + "px)";

or

listElements[i].style.right = "calc(33.333 * " + portfolioScrollPosition + "vw)";

or

listElements[i].style.right = "calc(50 * " + portfolioScrollPosition + "vw)";

I need it to be written into html embedded styles EXACTLY like this. However, the calc() is simplifying, and is just writing something like calc(425px). Is there any way to prevent JS from making this simplification?

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

0

Getting it into the rendered style sheet is tricky but adding it to an elements in-line style that reads as you want it when examined in developer tools can be done by using template literals (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)

Elemement.setAttribute("style", `right:calc(425 * ${portfolioScrollPosition}px;`);

If you really need it in the style sheet, you would have to change the inner text of the entire style element. <style></style> is like any other element, you can make a reference to it and change it's inner text using element.textContent = "" or element.innerText. It will be messy with a big style sheet.

Edit I've made a working example to illustrate the approach of re-writing the style element's innerText here: https://jsfiddle.net/DaveCP/8czrnhwe/1/ (the SO snippet tool has trouble with new line characters in a string).

In the example, the style rule aspect-ratio: calc(2 / 1); is re-written to aspect-ratio: calc(4 / 1)

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!