DEV Community

Cover image for Vue Tips: Dynamic CSS with Vue Reactive Variables
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

10 2

Vue Tips: Dynamic CSS with Vue Reactive Variables

If you use Vue, you might be used to having to apply different classes to tags based on the logic in your code. That's because we might want to reactively update an elements class based on when certain conditions. For example, suppose if a variable check is set to true, we want a div to show as red, but otherwise it should be blue. For such use cases, it's common to see the following code:

<div :class="check === true ? 'red' : 'blue'">
    Hello World
</div>
Enter fullscreen mode Exit fullscreen mode

Did you know, however, that you can actually put Vue reactive variables straight in your CSS with Vue 3? We have to use the composition API (read more: difference between composition and options API), but once we do, we can avoid the code below and put our variable straight in our CSS.

Let's look at a simple example. Suppose we have the following script in our Vue template:

<script setup>
import { ref } from 'vue'

const check = true;
let color = ref('#ff0000');

if(check == true) {
  color.value = '#0000ff';
}
</script>
<template>
  <input value="Hello World" />
</template>
Enter fullscreen mode Exit fullscreen mode

Simple, right? If check is true, the color variable is '#0000ff'. Otherwise it's '#ff0000'. In our CSS, with Vue 3, we can now directly reference color by using v-bind:

<style>
  input {
    color: v-bind(color)
  }
</style>
Enter fullscreen mode Exit fullscreen mode

Now if color updates reactively, the color of input will change to whatever the color variable is set to. That means you can avoid some awkward logic in your HTML tags, and start using Javascript variables straight in your CSS - and I think that's pretty cool.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more