Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda