murchu27
murchu27

Reputation: 579

Using CSS calc() in JavaScript with a variable

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?

Upvotes: 4

Views: 13208

Answers (3)

RCDAWebmaster
RCDAWebmaster

Reputation: 325

I finally got it, or so I thought:

window.onload = function() { resize(); }
window.onresize = function() { resize(); }

function resize() {
if (window.innerWidth >= 992){
    var H = window.innerHeight;
    H = H  - 250;
    H = H + "px";
    document.getElementById('article').style.minHeight =  H;
}
else if (window.innerWidth >= 768 && window.innerWidth <= 991){
    
    var H = window.innerHeight;
    H = H  - 237;
    H = H + "px";
    document.getElementById('article').style.minHeight =  H;  
}
else if (window.innerWidth >= 480 && window.innerWidth <= 767){
   
    var H = window.innerHeight;
    H = H  - 217;
    H = H + "px";
    document.getElementById('article').style.minHeight =  H; 
}
else if (window.innerWidth <= 479){
    
    var H = window.innerHeight;
    H = H  - 201;
    H = H + "px";
    document.getElementById('article').style.minHeight =  H; 
}
}

What I don't understand is why the footer on the phone is so far above the bottom of the page. I thought that javascript's window.innerHeight was supposed to get around the 100vh bug in CSS. what am I missing? It's almost as if I swapped one bug for another.

Upvotes: 0

diambakus
diambakus

Reputation: 95

var pad = `calc(${width} - 90px)`

This should also work.

Upvotes: 2

epascarello
epascarello

Reputation: 207501

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>

Upvotes: 5

Related Questions