In this tutorial, you’ll learn how to set background image using inline styles in Vue.js.
In Vue.js you can manipulate a DOM element’s inline styles as well as classes using v-bind:style
.
Here’s how you can set a background image using inline styles:
new Vue({
el: "#app",
data: {
image: 'https://picsum.photos/600/200'
}
})
First of all, let’s set an image src, we’ll be using a third-party random image generator Picsum.
<div id="app">
<h2>Inline background image in Vue.js:</h2>
<div v-if="image" style="width:600px; height:200px" :style="{ 'background-image': 'url(' + image + ')' }"></div>
</div>
As you can see, we’ve just set a background image using the :style
(a shorthand for v-bind:style
).
The result:
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-background-image
PS: Make sure you check other Vue.js tutorials, e.g. conditionally add HTML attributes in Vue.js.
Hi thank you for posting your solution. It is possible to generate that url encapsulated only with single quotes?
Now is it:
style=”width: 600px; height: 200px; background-image: url(“https://picsum.photos/600/200″);”
And i am not sure if is 100% correct to have double quotes inside double quotes in html.
Thank you for answer
Hi Radovan! In you example, you can just replace the inner quotes with a single quote. E.g.
style=”width: 600px; height: 200px; background-image: url('https://picsum.photos/600/200');”
But nowadays url quotes are optional. Only old browsers require them, so it’s pretty safe to delete them completely.
Actually, it depends on the file name. If your image file name might contain parenthesis, eg. my-image(2).jpg, then quotes in the url() declaration are not optional because the browser will ignore the background image.
Yes, makes total sense!