by Sai gowtham

How to set a background image in Nuxt

In this tutorial, we are going to learn about how to set a background-image in the nuxt app using inline styles and external css.

Setting the image using inline styles

About.vue
<template>
  <div :style="{ backgroundImage: `url(${image})`}">    <h1>This is the About page</h1>
  </div>
</template>

<script>
import bikeImg from "assets/bike.png";export default {
  data() {
    return {
      image: bikeImg,    };
  }
};
</script>

In the above example, first we imported the bikeImg from the assets folder and assigned it to the image data property.

Now inside the vue template, we added a background-image dynamically to the div element using : style directive object syntax.

Similarly, we can also store the entire object syntax inside the data property like this.

About.vue
<template>
  <div :style="image">    <h1>This is the About page</h1>
  </div>
</template>

<script>
import bikeImg from "assets/bike.png";export default {
  data() {
    return {
      image: { backgroundImage: `url(${bikeImg})` },    };
  }
};
</script>

Setting image using external CSS

We can also add a background image to the elements using the external css instead of inline styles.

Example:

About.vue
<template>
  <div class="container">    <h1>This is the About page</h1>
  </div>
</template>

<script>
export default {
};
</script>

<style scoped>
.container {
  background-image: url("~assets/bike.png");}
</style>

Note: The vue-loader automatically process your css styles using the css-loader, for example url("~assets/bike.png") translated into require("~assests/bike.png") .

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course