Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

378
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda