Daiaiai
Daiaiai

Reputation: 1089

Fallback for css-vars

I want to use CSS vars the first time and am doing that

#circle_1 {
  width: 50px;
  height: 50px;
  width: var(--size_1);
  height: var(--size_1);
}

and fill it with JS like so

var input_1 = document.querySelector("#groesse_1");
var circle_1 = document.querySelector("#circle_1");
input_1.addEventListener("change", function() {
  circle_1.style.setProperty("--size_1", input_1.value);
});

This works nice, but as long as the user doesn't add a value to input_1, the circles have a not defined size (which I tried to prevent by giving a default height/width in the CSS before I added the width: var(--size_1); thing)

How would I correctly add a default value to that element?

See here: https://codepen.io/daiaiai/pen/OQYwVW

Upvotes: 1

Views: 193

Answers (3)

Kaiido
Kaiido

Reputation: 136678

CSS func var() accepts two arguments: the --var custom property, and a fallback value.

So to properly fallback values you would do

selector {
  prop: 20px; /* for browser without support for variables */
  prop: var(--my_var, 20px); /* for browser with support for variables */
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074266

You can do that when defining the variable, and you only supply width and height once:

#circle_1 {
  --size_1: 50px;
  width: var(--size_1);
  height: var(--size_1);
}

In your event handler, you'll also need to specify units unless you're expecting the user to enter them, e.g.:

circle_1.style.setProperty("--size_1", input_1.value + "px");
// -------------------------------------------------^^^^^^^

...or similar.

More on MDN.

Live Example:

var input_1 = document.querySelector("#groesse_1");
var circle_1 = document.querySelector("#circle_1");
input_1.addEventListener("change", function() {
  circle_1.style.setProperty("--size_1", input_1.value + "px");
});
#circle_1 {
  --size_1: 50px;
  width: var(--size_1);
  height: var(--size_1);
  border: 1px solid black;
}
<input id="groesse_1" type="text">
<div id="circle_1"></div>

Upvotes: 1

John Baker
John Baker

Reputation: 2398

You can give a fallback default value

#circle_1 {
  width: var(--size_1, 30px);
  height: var(--size_1, 30px);
}

So this way the default value its 30px but if --size_1 its not empty it will override the 30px

If you want to know more here vars on MDN

Here is your updated codepen with a fallback

Upvotes: 1

Related Questions