Romy
Romy

Reputation: 31

Ionic2 background-image don't appear on device

I've set a custom class .categories e in my Ionic2 app in order to style it with a custom background. The CSS for the background is:

.categories {
  background: url('../../assets/img/dark.jpg');
  background-size: cover;
}

Everything works just fine in Chrome (using ionic serve), but when I build and run on device, all I see is a plain white background. I've tried adjusting the path for the background image to assets/img/dark.jpg but no luck. If anyone could possibly help me I'll appreciate your help.

Thank you in advance

Upvotes: 1

Views: 80

Answers (3)

Tomas Eklund
Tomas Eklund

Reputation: 633

Background information on the background-image problem

Ionic seems to take all your scss-files, transpile and merge them into one giant css-file (main.css) which is stored in the {project}/www/build/ directory.

If your background images originally reside in the {project}/src/assets/img/ directory, they are copied to {project}/www/assets/img/.

So regardless of where, or how deep, in the src directory tree your source scss-files are (commonly {project}/src/pages/{pagename}/{pagename}.scss) you need to consider that the paths of referenced images need to be relative to the build directory, not the directory of your scss-file.

When testing the app on a desktop browser using >ionic lab, absolute paths will also work, for example:

background-image: url('/assets/img/dark.jpg');

But in my experience this will not work on actual devices nor in emulators. So don't use it.

As Bouzafour Mohamed mentioned, you need to use the following format to reference your background image.

background-image: url('../assets/img/dark.jpg); 

Upvotes: 1

Bouzafour Mohamed
Bouzafour Mohamed

Reputation: 122

alright i think all what you have to do is to change the URL to

background-image: url('../assets/img/dark.jpg');

Upvotes: 1

Dr. X
Dr. X

Reputation: 2930

Link will be not like you used it has to be like relative path to your file

such as your file is on

src > pages > example >example.scss 

then you must use image path as

.categories {
background: url('../../assets/img/dark.jpg');
background-size: cover;
}

Upvotes: 0

Related Questions