I Cannot set background image in ionic 4 div from template

952 Views Asked by At

I am building a mobile app with ionic and I am trying to change the background image of the div but its not working

Here is the code

<div style="background-image: url(./assets/IMG/set3.jpg);">
......
</div>

I also changed the file path to

style="background-image: url(assets/IMG/set3.jpg);"

style="background-image: url(./assets/IMG/set3.jpg);"

style="background-image: url(/assets/IMG/set3.jpg);"

And I have other div of such, but the background image is not displaying, pls I need your help, I have search online but non of the solutions worked

3

There are 3 best solutions below

1
Ravindra On

If your goal is to set background image to the entire page, you could use --background for ion-content. Something like following has worked for me.

ion-content {
--background: url('../../assets/BackgroundImages/splash-screen-background.png');
background-position: center center;
background-size:contain;
background-repeat: no-repeat;
}

here are more details about --background CSS property

0
Ravindra On

Some IDEs (Visual Studio Code) allow you to ctrl click the url (follow link) and ensure that the resource is correctly pointed to. You may want to double check. Even otherwise please check if your assets folder is present at the same level as your page html. If it is not you may have to ensure the correct path, for ex.

background-image: url('../../assets/BackgroundImages/splash-screen-background.png');
0
MikeC On

Instead of setting the background-image directly with a style tag inside your <div>, give it a class. Then, inside your CSS, define the background-image on that class. That way, the IMG folder should be relative to the CSS file or the app-root. This always gets me with every new project, and it requires some trial and error to get it right.