How do I link a static image inside a css file?

newb for pyramid and python. I was able to successfully link my static files in any of my jinja2 templates, i.e.:

<link rel="stylesheet" type="text/css" href="{{'myproject:static/mycss.css'|static_url}}"></link> 

The .css file loads fine, and I can reference any images that are inside my static folder while I do this in the jinja template.

I would like to use the image as a background, but I had problems with linking to the image in my css file:

 #mydiv{ background-image:url("{{'myproject:static/myimage.gif'|static_url}}"); } 

This link appears in mycss.css as

"{{'myproject:static/myimage.gif'|static_url}}"

and does not appear as a link. (if I load an external hosted image as a background image that it works)

THX!

+7
source share
1 answer

Your CSS file is a static file and therefore is not considered a template. All static resources are served as is, without any processing.

All non-absolute URLs in the CSS file refer to the location from which the CSS file was loaded; if you use background-image:url("myimage.gif") , the browser downloads the image relative to your CSS file location. Since CSS was downloaded from http://yoursite/static/mycss.css , the image will be downloaded from http://yoursite/static/myimage.gif .

Alternatively, if you link to files from unusual places (for example, images autogenerated by one of your views), you will have to add your CSS file as a view instead and make it using a (text) template.

+11
source

All Articles