Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS calc() in JavaScript with a variable

Tags:

javascript

css

User NickC asks here if it is possible to set an element's position (or similar style properties) in js using CSS's calc() function.

Example:

var pad = "calc(1250px - 1000px)";
element.style.paddingLeft = pad;

This shows up just fine on my web page, but I would like to include a js variable in the function, like so:

var pad = "calc("+ width +"- 1000px)";
alert(pad); //displays calc( 1250px - 1000px)
element.style.paddingLeft = pad;

I included the alert statement to assure myself that the string itself was correct, which it appears to be. However, the desired padding does not appear.

Is there a problem with what I'm doing, or is it just not possible to do this?

like image 297
murchu27 Avatar asked Nov 02 '25 00:11

murchu27


1 Answers

Problem you have is a simple issue with a missing character. Without it, there is no padding, with it there is.

var width = '100px'


var element1 = document.getElementById("test1")
var element2 = document.getElementById("test2")

var pad1 = "calc(" + width + "- 90px)";  //what you have
var pad2 = "calc(" + width + " - 90px)"; //what it should be

element1.style.paddingLeft = pad1;
element2.style.paddingLeft = pad2;
div {
  background-color: red
}
<div id="test1">
  Hello 1
</div>
<div id="test2">
  Hello 2
</div>
<div>
  Hello d
</div>
like image 82
epascarello Avatar answered Nov 03 '25 14:11

epascarello