1

Trying to use Window.innerWidth and load the received value into a CSS variable, but it does not seem to work. What am I doing wrong?

function myFunction() {

  var w = window.innerWidth;
  
  document
    .documentElement
    .style
    .setProperty('--window', w);
}
:root {
  --window:0px;
}

div {
  
  height: calc(var(--window) / 2);
  background: red;
  
}
<div></div>

2
  • I think you have to write a new stylesheet. Commented Jan 13, 2021 at 17:57
  • If an answer was helpful to you, you should accept it with the checkmark on the left of it. Commented Nov 15, 2022 at 15:59

2 Answers 2

2

Two reasons:

  1. You are not calling myFunction, only defining it.
  2. window.innerWidth returns a number without units (which represent pixels). In order for it to be a valid height value, you should add px as a suffix.

function myFunction() {
  var w = window.innerWidth;
  document.documentElement.style.setProperty('--window', `${w}px`);
}
myFunction();
:root {
  --window: 0px;
}

div {
  height: calc(var(--window) / 2);
  background: red;
}
<div></div>

Another thing you might not know: var() accepts a default value. If --window is only used once, you can write the property as height: calc(var(--window, 0px) / 2); and omit the :root ruleset.

Sign up to request clarification or add additional context in comments.

Comments

1

You can add the rule dynamically, to the style-sheet using a insertRule or addRule.

Please review "Add Rules to Stylesheets with JavaScript" by David Walsh.

// See: https://davidwalsh.name/add-rules-stylesheets
const addCSSRules = (sheet, selector, rules, index = 1) => {
  if (typeof rules !== 'string') {
    rules = Object.entries(rules).map(entry => entry.join(':')).join(';');
  }
  if ('insertRule' in sheet) {
    sheet.insertRule(`${selector} {${rules}}`, index);
  } else if ('addRule' in sheet) {
    sheet.addRule(selector, rules, index);
  }
}

const [ sheet ] = document.styleSheets;

addCSSRules(sheet, ':root', {
  '--window': `${window.innerWidth}px`
});
:root {
  --window: 0px;
}

div {
  height: calc(var(--window) / 2);
  background: red;
}
<div></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.