I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:
apps/assets/stylesheets/main.scss
I wanted to render background image in header tag. The following was my original implementation.
header {
text-align: center;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('../images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:
ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)
I tried different variations of the url:
url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK
and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:
url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED
I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...
header {
text-align: center;
height: 390px;
background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
url('images/header.jpg') no-repeat;
background-blend-mode: multiply;
background-size: cover;
}
Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.
It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.