YouTip LogoYouTip

Vue Class Style

# Vue.js Style Binding ## Vue.js class class and style are attributes of HTML elements used to set the element's styles. We can use v-bind to set style attributes. Vue.js v-bind has been specifically enhanced when handling class and style. The result type of the expression can be an object or an array, in addition to a string. * * * ## Class Attribute Binding We can set an object for v-bind:class to dynamically toggle classes: ## Example 1 In this example, setting isActive to true displays a green div block; setting it to false does not display it:
[Try it Β»](#) The div class in the above example is:
We can also pass more properties in the object to dynamically toggle multiple classes. ## Example 2 The text-danger class background color overrides the active class background color:
[Try it Β»](#) The div class in the above example is:
We can also directly bind to an object in the data: ## Example 3 The text-danger class background color overrides the active class background color:
[Try it Β»](#) Example 3 has the same rendering result as Example 2. Additionally, we can bind to a computed property that returns an object. This is a common and powerful pattern: ## Example 4 new Vue({el: '#app', data: {isActive: true, error: {value: true, type: 'fatal'}}, computed: {classObject: function(){return{base: true, active: this.isActive&& !this.error.value, 'text-danger': this.error.value&&this.error.type === 'fatal', }}}}) [Try it Β»](#) ### Array Syntax We can pass an array to **v-bind:class**, as shown in the following example: ## Example 5
[Try it Β»](#) The div class in the above example is:
We can also use a ternary expression to toggle classes in the list: ## Example 6 errorClass is always present; activeClass is added when isActive is true:
[Try it Β»](#) * * * ## Vue.js style (Inline Styles) We can set styles directly in **v-bind:style**: ## Example 7
Tutorial
[Try it Β»](#) The div style in the above example is:
Tutorial
We can also bind directly to a style object to make the template cleaner: ## Example 8
Tutorial
[Try it Β»](#) v-bind:style can use an array to apply multiple style objects to an element: ## Example 9
Tutorial
[Try it Β»](#) > Note: When **v-bind:style** uses CSS properties that require specific prefixes, such as transform, Vue.js will automatically detect and add the appropriate prefixes.
← Vue EventsVue Directory Structure β†’