Home > Mobile >  How to present a backgound image with css
How to present a backgound image with css

Time:10-05

I am trying to add an background image with css but I am geting 404 error

GEThttp://127.0.0.1:5500/css/img/example.jpg

Here is the code that I use.

body {
    background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(img/example.jpg);
    background-size: cover;
    background-position: center;
    height: 100vh;
} 

The image is in the folder img and the name is correct.

CodePudding user response:

The path may be correct, but not if the css is the starting point So firstly you have to go up a level with "../" in front of your current path. So "../img/example.jpg"

(Maybe you have to go up several levels, depending on where exactly your folder lies, you would need to show your folder structure for more insight if this doesn't fix it)

CodePudding user response:

If this is a CSS file, the image file is relative to the css file, not the html.

CodePudding user response:

url accepts the path relative to / (document root of the web server where website is deployed) or to the CSS file.

So if you change the line by adding /css:

background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(img/example.jpg);

to

background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0,0.7)), url(/css/img/example.jpg);

it should work. Absolute paths are usually better.

For more information please see:

https://developer.mozilla.org/en-US/docs/Web/CSS/url

  • Related