Home > Software design >  My CSS custom property variables are not working
My CSS custom property variables are not working

Time:01-05

I'm defining these variables in a :root

:root {
    --hue:271;
    --saturation: 75%;
    --foregroundColor: hsl(var(--hue), var(var(--saturation)), 75%)
    --backgroundColor: hsl(var(--hue), var(var(--saturation)), 30%)
}

and using them here:

.ball {
    --x: 50;
    --y: 50;

    position: absolute;
    background-color: var(--foreground-color);
    transform: translate(-50%, -50%);
    top: calc(var(--y) * 1vw);
    left: calc(var(--x) * 1vh);
    width: 2.5vh;
    height: 2.5vh;
}

The .ball and anything else using the variables stays the color white when it should be a purple. I am a beginner and I'm not sure what to do. I'm running on Chrome. No error messages.

CodePudding user response:

There are several errors in the given CSS.

var(var(--saturation))

missing semi colon at the end of a CSS property setting

defining --foregroundColor and --backgroundColor but using --foreground-color and --background-color.

Using your browser's dev tools inspect facility and hovering over the variabes where used in the styles you should have seen some as 'undefined'.

Try:

:root {
    --hue:271;
    --saturation: 75%;
    --foreground-color: hsl(var(--hue), var(--saturation), 75%);
    --background-color: hsl(var(--hue), var(--saturation), 30%);
}


.ball {
    --x: 50;
    --y: 50;

    position: absolute;
    background-color: var(--foreground-color);
    transform: translate(-50%, -50%);
    top: calc(var(--y) * 1vw);
    left: calc(var(--x) * 1vh);
    width: 2.5vh;
    height: 2.5vh;
}

Note: top is calculated in terms of viewport width and left in terms of viewport height. I can't tell whether this is intentional or a bug.

As well as using your browser dev tools to search for errors or warnings or undefined properties it's also worth putting your code through a checker (e.g. W3C validators).

CodePudding user response:

Typo: foregroundColor instead of foreground-color

:root {
    --hue:271;
    --saturation: 75%;
    --foregroundColor: hsl(var(--hue), var(var(--saturation)), 75%)
    --backgroundColor: hsl(var(--hue), var(var(--saturation)), 30%)
}


.ball {
    --x: 50;
    --y: 50;

    position: absolute;
    background-color: var(--foregroundColor);
    transform: translate(-50%, -50%);
    top: calc(var(--y) * 1vw);
    left: calc(var(--x) * 1vh);
    width: 2.5vh;
    height: 2.5vh;
}

  •  Tags:  
  • Related