skip to Main Content

I am working on a nuxt3 project and want to use an image as the background, but I am stuck with the problem of it not showing up on my screen.

I placed my image as documented in Nuxt3.

So I tried:

<template>
    <div class="custom-background-image">
    </div>
</template>

<script setup>

</script>

<style scoped>
    .custom-background-image {
        background-image: url('~/assets/images/some-image.jpg');
    }
</style>

But there is no image showing up on my screen. Did someone ecountered the same problem?

2

Answers


  1. If you store your images inside the assets folder. You can do it like this in your CSS.

    ~/assets/images/background.png

    .custom-background-image {
        background-image: url('~/assets/images/background.png');
    }

    But if you store your images file in a static or public folder, you can call the background image like this.

    ~/public/assets/images/background-image.jpg

    .custom-background-image {
        background-image: url('/assets/images/background-image.jpg');
    }

    Tested and it works.

    PS: you need to add height on your .custom-background-image class to show the background image. e.g height:100vh;

    Login or Signup to reply.
  2. Your problem is due to the default "height=0" and "width=0" "div", if you set the style like the code below, you can see the image.

    <style scoped>
    .custom-background-image {
      width: 200px;
      height: 200px;
      background-position: center center;
      background-size: contain;
      background-repeat: no-repeat;
      background-image: url('~/assets/images/some-image.jpg');
    }
    </style>
    

    but if your div gets the content it will show the image because it will get the height and width automatically.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search