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
<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.
<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:
<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 exampleurl("~assets/bike.png")
translated intorequire("~assests/bike.png")
.