Most Common Ways to Bind Dynamic CSS Styles in VueJs
Sometimes it happens that we need to load a different CSS style depending on a particular situation and for that, we have to know how to use dynamic CSS style bindings.
There will be very often situations where you might need to use some dynamic classes in VueJs. It can be rendering of a different color depending on the choice of the user or even a different image.
But how exactly can you do that in VueJs? Let’s take a look at different examples.
Ternary expression
One of the most common ways to render conditional dynamic CSS classes is to use ternary expressions. You can do that when you have only two styles between which you want to toggle.
<div :class="isUser ? userClass : guestClass "></div>
In this situation we check if the variable “isUser” is true, if it is the case, we apply “userClass” to our element, and if it is not we have a “guestClass” applied to it.
❗️Please note, that if you want to use any conditional classes, do not forget to bind them and to add the “:” in front of the class.
Methods
If you have a list of users, for example, and you want to apply a different color on each user depending on how active is this user, you can use methods in order to render different colors.
Let’s say, you have five different colors and you need to apply one of them to the user, depending on his activity.
<div :style="backgroundColor: statusColor(user.activity)"></div>
methods: { statusColor(activity) {
let color;switch (activity) {
case 1:
color = "red"
break;
case 2:
color = "green"
break;
case 3:
color = "yellow"
break;
case 4:
color = "orange"
break;
case 5:
color = "violet"
break;
default:
color = "grey";
}}
return color;},}
Here, as you can see, we have used style and applied a background color of our div element. That means that we take information about our user activity, pass it as an argument to our Method, and loop through the different cases, as soon as the case corresponds to our user’s activity, it assigns the color we need.
At the end of the function, it is important to return the value that we got from the looping.
Dynamic inline styles
Another useful solution can be also the usage of dynamic inline styles. Let’s say you have a dynamic variable to set on the width of the element.
<div :style="{ width: width + 'px' }"></div>data() {
return {
width: 300
}
}
By using this way of setting the dynamic styles you can take any number and apply it to our width. It can also be a dynamic number coming from data that we are getting or a number changing when, for example, the user clicks on the button.
It can exist a variety of different other examples but for me, those were the most common that I was using while working on the project.
Happy coding! 😊