Styling with Inline CSS Styles in Vue.js

Published on March 13, 2017 by

So far we have seen quite quite a few examples, but let’s be honest, they haven’t been that visually appealing. In the next couple of lectures, we are going to see how we can apply styling to our elements and make things just a bit more interesting. We are first going to start out by adding inline styles to elements with the style HTML attribute. Since we are going to bind to an HTML attribute, we are going to use the v-bind directive again.

I have added a simple div in advance which is 200 pixels in width and height, and the first thing I want to do, is to set its background color to blue.

<div style="width: 200px; height: 200px;" v-bind:style=""></div>

When binding to the style attribute, the expression can either be an object or an array. Let’s begin by seeing what the object syntax looks like. The keys in this object should match the CSS style that we want to set, and the value should be an expression that resolves to a value. In this case, the key will be background-color. As in normal JavaScript, we need to enclose the key within quotation marks because it contains a dash. Note that I will use single quotes here so I don’t have to escape double quotes, as they would otherwise interfere with the HTML markup.

So that was the name of the style that I want to apply to the div element. For the value, I can simply write red enclosed in single quotes as well.

<div style="width: 200px; height: 200px;" v-bind:style="{ 'background-color': ‘red’ }"></div>

This will give us a red square.

Of course this is not all that useful, because we defined the color directly within our template. If that’s all we needed, we might as well just have added the style directly to the HTML style attribute. What’s more useful, is to actually bind to a dynamic color. Let’s create a data property containing the color instead and bind to this property within the template.

data: {
	color: 'blue'
}

Now I just need to write the name of this property as the expression for the background-color style, and the result will be the same.

<div style="width: 200px; height: 200px;" v-bind:style="{ 'background-color': color }"></div>

Now of course this is not too useful either, because we have hard coded the color within our Vue instance. But what this enables us to do, is to change the color dynamically. And, you guessed it, when doing this, Vue.js will automatically update the style, because we have now bound the background-color style to the color data property. To show you this, I will add a button with a click event listener which changes the color.

<button v-on:click="changeColor">Change Color</button>

And now the event listener. This listener will simply use an if statement to switch the color from blue to red and vice verca.

methods: {
	changeColor: function() {
		if (this.color == 'blue') {
			this.color = 'red';
		} else {
			this.color = 'blue';
		}
	}
}

If I click the button now, we will see that the background color of the div changes.

As you can probably imagine, it can quickly become difficult to read if we add more properties to the object within the template. To solve this, we can simply move the object to a data property and refer to this property within the template. I will call the property styles.

In the process I will clean up the code a little, because we will no longer need the button that changes colors.

data: {
	styles: {
		'background-color': ‘blue’
	}
}

With this, I can simply write styles as the expression within the template.

<div style="width: 200px; height: 200px;" v-bind:style="styles"></div>

Before proceding, did you notice that we have a style attribute in pure HTML alongside the binding to the same HTML attribute? This works because Vue.js merges the styles on our behalf before applying the styles to the DOM. So the styles that are applied to the DOM are the result of merging the HTML style attribute with our style binding. The same applies when using classes, which we will see in the next post.

That being said, let’s move the width and the height to this styles object as well, just to keep the styles in one place and thereby make things a little easier to maintain.

styles: {
	'background-color': 'blue',
	width: '200px',
	height: '200px'
}
<div v-bind:style="styles"></div>

Much better! This is all great for simple examples like this, but what if we needed to make use of some other data properties to determine the styles? Perhaps we always want the width to be half of the height. Of course we could be lazy and just change the width to 100 pixels, but that woundn’t be much fun, would it? Since we cannot access other data properties from within our styles object, we need to do something else. Can you guess it? The answer is a computed property. So let’s change our data property to be a computed property instead.

computed: {
	styles: function() {
		var height = 200;
    
		return {
			'background-color': 'blue',
			width: (height / 2) + 'px',
			height: height + 'px'
		};
	}
}

Now we will see that the width is half of the height. The point is that you can either use a data property if your styles do not depend on one another, or a computed property if they do.

I mentioned that it is also possible to use an array for the styles instead of an object. This is perhaps slightly less common, but let’s take a look at how to do it anyways.

If we add an array instead of an object, this array should in fact be an array of objects, where each object uses the same syntax as we have just seen. The point of this is that you can override styles. So I add a new data property named moreStyles which adds round corners to the div by using the border-radius CSS style.

data: {
	moreStyles: {
		'border-radius': '5px'
	}
}

In the template, I can now add the two objects within an array.

<div v-bind:style="[styles, moreStyles]"></div>

I could of course also have referred to either a data property consisting of an array, or a computed property which returns an array.

What this does, is that it merges the two objects together, so if I run the code, you will see that the div still has the same styles, but that it now also has round corners. This is because Vue.js merges the objects together, and it is worth noting that an object in the array takes precedence over any objects added before them. So if I were to change the background color to red within the moreStyles object, we would see that the background color changes to red, even though we had already defined it to be blue in the first object.

data: {
	moreStyles: {
		'border-radius': '10px',
		‘background-color’: ‘red’ // REMOVE AFTER RUNNING CODE
	}
}

Something interesting to note, is that Vue.js automatically prefixes the CSS styles with any vendor specific prefixes to ensure maximum browser compatibility. This means that when using inline styles like this, Vue.js got you covered so you don’t need to worry about using tools like autoprefixer, which can be difficult to use with inline styles.

And with that, let’s move on to seeing how we can apply styling with CSS classes.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

One comment on »Styling with Inline CSS Styles in Vue.js«

  1. Martin

    Thank you for the video. Well explained, clear and concise. Super helpful to understand how this binding works. Keep it up!

Leave a Reply

Your e-mail address will not be published.