Add Background Image in Vue.js with Examples

Published on December 24, 2019 34 sec read

In this guide, I’ll show some ways to set background image in Vue.js. Let’s see the ways with examples:

Example 1

We are able to set inline background image in kebab-case and camelCase properties.

Kebab-case:

<div :style="{'background-image':'url(https://example.com/bg.png)'}"></div>

camelCase:

<div :style="{backgroundImage:'url(https://example.com/bg.png)'}"></div>

Example 2

If we need to display background image from server-side, we can show like this way:

<div :style="{backgroundImage:`url(${article.image})`}"></div>

Example 3

We can set background image using vue data property. Let’s see the example:

<template>
    <section>
        <div :style="image" class="image"></div>
    </section>
</template>

<script>
    export default {
        data() {
            return {
                image: {backgroundImage: "url(https://via.placeholder.com/150)"}
            };
        }
    };
</script>

<style>
    .image {
        height: 150px;
        background-repeat: no-repeat;
    }
</style>

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *