Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCSS/CSS background-image url path problem

Tags:

html

css

sass

I have an SCSS project and I need to use background-image property on a div, but it doesn't find the image. (CSS is properly linked). This is my SCSS code:

.coffee-icon {
    background-image: url('./../img/coffee.png') no-repeat;
    width: 400px;
    height: 400px;
    background-size:cover;
}

and this is the folder structure:

project folder structure

Some notes at the end: it doesn't work with "", or without quotes, and I'm pretty sure it is a problem with path, I just don't know what it is the problem.

like image 372
Michal Gally Avatar asked Mar 29 '26 19:03

Michal Gally


1 Answers

In a perfect world your URL paths should be absolute, so always starting with / refering to the base path of the domain.

You have:

background-image: url('./../img/coffee.png') no-repeat;

The shape you should be looking for is:

 background-image: url('/folder/img/coffee.png') no-repeat;
                        ^ This lead slash references the base path of the domain.

So, the above example is domain.com/folder/img/coffee.png - you see the leading / is the base the whole URL is based from.

The advantage of this is your SCSS or CSS or image files can be placed in any location in your domain structure.

Absolute Pathing is the key to success!

Example 2:

 background-image: url('/images/tea.png') no-repeat;

Image is located at:

 mydomain.org/images/tea.png 

The location of the SCSS or CSS file is not important, as long as it's on the same domain.

like image 144
Martin Avatar answered Mar 31 '26 10:03

Martin