1

I'm new at VF develop. please help.

I loaded many image in VF like below, and it works well.

<apex:image alt="s01" title="s01" url="{!URLFOR($Resource.resource_images, '/s01.PNG')}"/>

However, currently I need load image in css file. I searched many related articles and tried like below.

.qna { 
background-image: url("{!URLFOR($Resource.resource_images, '/s01.PNG')}");  }

and it doesn't work..

Anybody know why it doesn't work?

Thanks in advance.

1 Answer 1

2

The syntax below:

{!URLFOR($Resource.resource_images, '/s01.PNG')}

will only be resolved when you use it directly in the markup on the Visualforce page. If you need to provide the image name in the CSS file, then you will need to utilize the relative path of the image in the CSS. The syntax in your case will be as:

.qna { background-image: url('<path>/s01.PNG') }

For more details, refer to Referencing a Static Resource in Visualforce Markup documentation which details as how you can create a CSS with relative image path and utilize those on a VF page.

Excerpt below from the documentation:

You can use relative paths in files in static resource archives to refer to other content within the archive. For example, in your CSS file, named styles.css, you have the following style:

table { background-image: url('img/testimage.gif') }

When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create an archive (such as a zip file) that includes styles.css and img/testimage.gif. Make sure that the path structure is preserved in the archive. Then upload the archive file as a static resource named “style_resources”. Then, in your page, add the following component:

<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>

Since the static resource contains both the style sheet and the image, the relative path in the style sheet resolves and the image is displayed.

4
  • Hi Jayant. You mean, syntax is not a problem. Only relative path can be used in c.ss file, and if I try my ocde in .page file,I will be work. Is it right that I understand? Commented Dec 20, 2018 at 4:34
  • The syntax with URLFOR will only work on the VF page, same as you have in <apex:image ...>. If you specify that in CSS it won’t work. For referring an image in CSS you need to refer it using relative path as mentioned in the answer. Hope it helps.
    – Jayant Das
    Commented Dec 20, 2018 at 4:39
  • I uploaded css and image file as different static resources. In this case, as I know we cannot use relative URL. Do I need to set static resource again as 1 static resource? Commented Dec 20, 2018 at 5:07
  • Yes. Refer to the documentation except above which mentions that.
    – Jayant Das
    Commented Dec 20, 2018 at 5:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .