BinkyNichols
BinkyNichols

Reputation: 586

CSS calc() in JavaScript

I need to mix units in a dynamically generated div, but this doesn't render (IE left is still the default after that line is executed).

var tab3 = document.createElement('div');
tab3.className = 'tab';
tab3.style.display = 'none';
tab2.style.left = 'calc(~"200px+40vw")px';

Upvotes: 2

Views: 862

Answers (1)

Ori Drori
Ori Drori

Reputation: 193027

You've got several mistakes in your calc expression:

calc(~"200px+40vw")px -> calc(200px + 40vw)

  1. According to @JohnWeisz's comment - calc(~"200px+40vw")px is a Less expression, ~"..." is used to prevent Less from processing the addition operation from the source stylesheet files, but that's both invalid syntax and unnecessary from CSS string context.
  2. @G-Cyr adds that white space is required on both sides of the + and - operators. The * and / operators can be used without white space around them.

Example:

var tab3 = document.createElement('div');
tab3.className = 'tab';
tab3.style.left = 'calc(20px + 40vw)';
  
document.body.append(tab3);
.tab {
  position: absolute;
  width: 20vw;
  height: 20vh;
  background: red;
}

Upvotes: 4

Related Questions