Getting Started with Vue.js: Lesson 10 of 25

Applying Styles with Vue

Up Next

Vue Events: Build a Counter

Autoplaying in 7 seconds!

Cancel

In the previous lesson, we were able to apply CSS classes to our HTML. In this lesson, we will apply styles directly to the element.

While we talked about using JavaScript to only apply CSS classes, there may be some instances where you want to apply styles directly. One instance could be if you are listening for mouse movement and want to change an elements positioning based on that mouse movement. This would be something like making eyes move to follow a cursor on a page.

To apply styles using Vue, you can v-bind:style.

Table of Contents

    Inline Object

    <div class="notification" v-bind:style="{ color: myColor, fontSize: mySize, backgroundColor: myBgColor }">
        I am a notification!
    </div>

    Object Styles

    The syntax to use an object instead of the styles is similar to how we did the same with classes:

    <div class="message">
        <div class="message-body" :style="myMessageStyles">
            I am a notification!
        </div>
    </div>
    const app = new Vue({
        el: '#app',
        data: {
            myMessageStyles: {
                color: '#EEE',
                fontSize: '20px',
                backgroundColor: '#555'
            }
        }
    });

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.