[SalesForce] Loading image in static resource within css

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.

Best Answer

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.

Related Topic