vue cli 3 – use background image in style tag
Make sure the image extension is lowercase. If the image has an uppercase extension, change it to be lowercase otherwise it won't work.
<style lang="scss">
.section{
background-image: url('~@/assets/photos/DSC08611.jpg'); //WORKED!
background-image: url('~@/assets/photos/DSC08611.JPG'); //DID NOT WORK
}
</style>
I would recommend using style binding. I found this thread really helpful link.
Here an example using bootstrap cards
<div
class="card-image"
:style="{ backgroundImage: 'url(' + require('@/assets/images/cards.jpg') + ')' }">
The image is in src/assets/images/cards.jpg
As Max Martynov, highlighted in the comments, you should use url('~@/assets/image.svg')
.
Webpack has some specific rules when resolving assets[1].
In order to resolve an alias (@
), as you are using, it is mandatory webpack handles the request as a module request. Using the prefix ~
enforces webpack to treat the request as a module request, similar to require('some-module/image.svg')
.
References
- https://vuejs-templates.github.io/webpack/static.html#asset-resolving-rules