DEV Community

Cover image for Setting css variable in VueJs
voronovam
voronovam

Posted on

Setting css variable in VueJs

Hi🤚

In this tutorial I will show you how to set css variable in VueJs application.

Sometimes we need to change color text and/or background of our elements. To make it I change value of css variable according to the condition.

Full DEMO

Change window with to see result.

CSS Variables

I created css variables: --bg-color and --text-color and using like this:

background-color: var(--bg-color)
color: var(--text-color)
Enter fullscreen mode Exit fullscreen mode

Computed VueJs

In VueJs I use computed field cssColors with this conditions:

cssColors() {
      if (this.width > 1000) {
        return {
          "--bg-color": "#212121",
          "--text-color": "#fff",
        };
      }

      if (this.width > 500 && this.width < 1000) {
        return {
          "--bg-color": "#FF00E5",
          "--text-color": "#2DFFE6",
        };
      }

      return {
        "--bg-color": "#fff",
        "--text-color": "#000",
      };
    },
Enter fullscreen mode Exit fullscreen mode

Method VueJs

For watching window width i using method getWidth and get window.innerWidth like this:

getWidth(e) {
  this.width = window.innerWidth;
},
Enter fullscreen mode Exit fullscreen mode

Source code

About me

I`m designer and frontend developer. My github.

Top comments (0)