问题
I want to paste a relative image url to a div to set it as the background image. Unfortunately the div won't render the image. So this works fine and renders the image
<img src="../assets/images/HeroImg.jpg">
but this one doesn't
<div style="background-image: url(../assets/images/HeroImg.jpg)">
Content goes here
</div>
Things I also tried:
- wrapping the url inside single quotes
assets/images/HeroImg.jpg
maybe?./assets/images/HeroImg.jpg
starting from the src folderimages/HeroImg.jpg
and./images/HeroImg.jpg
starting from the assets folder
What is the correct url to use for background images?
Update
I'm using VueJs so things might be different here? Steps to reproduce:
- Create a new project using the Vue CLI
- Create a
images
directory insrc/assets
- Create an image in
src/assets/images
and call itHeroImg
- Update App.vue file with
.
<template>
<div id="app">
<div>
This works:
</div>
<div>
<img src="./assets/images/HeroImg.jpg">
</div>
<div>
This doesn't work:
</div>
<div style="background-image: url('./assets/images/HeroImg.jpg')">
Content without background image
</div>
</div>
</template>
You will see that the img tag renders the image but not the div with the background image.
回答1:
When you're using relative paths, Webpack is unable to resolve them properly if they are found inside your inline style
attributes. Webpack, can, however, resolve the image path properly if it is use as an <img>
element source in the template directly. Therefore, the solution to use a resolved image path as a CSS attribute is to simply reference it as a computed property.
In your template, you can use v-bind:style="heroImage"
to reference a computed property:
<template>
<div id="app">
<div v-bind:style="heroImage">
Content without background image
</div>
</div>
</template>
Then, in your VueJS component itself, you can do:
computed: {
heroImage() {
return {
backgroundImage: `url${require('../assets/images/HeroImg.jpg')}`
};
}
}
回答2:
html
<div class="yourDivClass">
Content goes here
</div>
css
.yourDivClass {
background: url('../assets/images/HeroImg.jpg') no-repeat center center / cover
}
回答3:
You should wrap them with quotes.
From MDN, we need to wrap the path or url of the image into a
background-image: url("../../media/examples/lizard.png");
<div style="background-image: url(../assets/images/HeroImg.jpg)">
Content goes here
</div>
Suggestion:
Better to avoid the inline styles. you can include the style in an external sheet.
回答4:
I think you have not specified height and width property.
div {
width: 60px;
height: 60px;
border: 1px solid black;
}
<div style="background-image: url(https://s3.amazonaws.com/media.skillcrush.com/skillcrush/wp-content/uploads/2017/04/Blog_coding-game.jpg.webp)"></div>
来源:https://stackoverflow.com/questions/60916989/how-to-set-background-image-url-for-local-files