Konrad
Konrad

Reputation: 15

CSS background image does not show when relative path used

I'm working on project in JavaFX. File structure looks like this (CEP is the root):

CEP
  +img
     menu.jpg
  +src
     +css_files
        MainMenu.css

What I want to do is to set background image from img directory in MainMenu.css file. So far I have tried different urls (see below), but none of them worked.

-fx-background-image: url("./CEP/img/menu.jpg");
-fx-background-image: url("../CEP/img/menu.jpg");
-fx-background-image: url("CEP/img/menu.jpg");
-fx-background-image: url("/CEP/img/menu.jpg");
-fx-background-image: url("../../img/menu.jpg");
-fx-background-image: url("/img/menu.jpg");
-fx-background-image: url("./img/menu.jpg");
-fx-background-image: url("../img/menu.jpg");
-fx-background-image: url("img/menu.jpg");

If I use full path like this

-fx-background-image: url("file:///C:/Users/Konrad/Desktop/java/CEP/img/menu.jpg");

everything works fine but that is not what I want to do. How can I load my background image using relative path?

Edit. As requested, here is build folder structure:

build
   +classes
      +css_files
      +(other folders)
      menu.jpg
   +empty (empty)
   +generated-sources (has 1 empty subfolder)

Upvotes: 0

Views: 2559

Answers (1)

James_D
James_D

Reputation: 209459

Your img folder, and its contents, are not part of your source folder hierarchy, and consequently are not being deployed as part of the application. You can either configure your IDE to deploy the contents of that folder, or more simply move img (and its content) into src.

If you do the latter, then img will be at the root of the classpath after deployment, alongside css_files, so either of

-fx-background-image: url("/img/menu.jpg");

or

-fx-background-image: url("../img/menu.jpg");

should work.

On the other hand, if you configure img as a source folder, then the contents of img will be placed at the root of the classpath. In this case, that means menu.jpg will be at the root of the classpath, so you would need one of

-fx-background-image: url("/menu.jpg");

or

-fx-background-image: url("../menu.jpg");

Upvotes: 1

Related Questions