How To Dynamic Style and Class Bindings in Vue.js Example

  • 14-08-2022
  • 801
  • Vue
  • Haresh Chauhan

In this vuejs tutorial, we will learn dynamic class and style bindings, It is very simple to use and fun to learn exercise. You can use dynamic property value in binding class and styling.

Vuejs common need for data binding is manipulating the element's class list and inline styles. Since style and class both are attributes, we can use the binding method v-bind to assign them string values dynamically. The latest we can short define like :class="{variable}" and :style="{variable}".

Binding to Objects

Class and Style Bindings; This vuejs binding style and class dynamic in the vuejs component. We can pass class with bind :class it short of (v-bind:class) to dynamic toggle progress class.

<div :class="{ active: isActive }"></div>
data() {
    return {
        isActive: true,
    }
}

Dynamic Style Binding

We can bind the style using a column. Just pass the object and give value to each attribute value.

<template>
    <div>
        <div :style="{ color: activeColor, fontSize: fontSize + 'px' }">Webappfix</div>
    </div>
</template>
    
<script>
export default {
    name:'HomeDashboard',

    data() {
        return {
            activeColor:'red',
            fontSize:60
        }
    }
}
</script>

Dynamic Style Binding Object

Bind style with full array as an object in the style attribute. We just need to define that array with key and value, The key will be the CSS property name and the value will be the value of attribute.

<template>
    <div>
        <div :style="styleObject">Webappfix</div>
    </div>
</template>
    
<script>
export default {
    name:'HomeDashboard',

    data() {
        return {
            styleObject: {
                color: 'red',
                fontSize: '150px'
            }
        }
    }
}
</script>

Binding to Arrays

We can also pass array in the style attribute, Bind style attribute and give them.

<div :style="[baseStyles, overridingStyles]"></div>

Multiple Values

We can give multiple values to a single property. We need to give the array to CSS properly.

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :