简体   繁体   English

如何链接到css文件中的静态图像?

[英]How do I link to a static image inside a css file?

newb to pyramid and python. newb to pyramid and python。 I've been able to link to my static files successfully in any of my jinja2 templates, ie: 我已经能够在我的任何jinja2模板中成功链接到我的静态文件,即:

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

The .css file loads fine and I can link to any images that are inside my static folder as long as I do it within the jinja template. .css文件加载正常,我可以链接到我的静态文件夹中的任何图像,只要我在jinja模板中这样做。

I'd like to use an image as a background but am having trouble linking to the image in my css file: 我想使用图像作为背景,但在链接到我的css文件中的图像时遇到问题:

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

This link shows up in mycss.css as 此链接显示在mycss.css中

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

and doesn't show up as a link. 并且不会显示为链接。 (if I load an externally hosted image as my background-image it works) (如果我加载外部托管的图像作为我的背景图像,它的工作原理)

thx! 谢谢!

Your CSS file is a static file, and thus is not treated as a template. 您的CSS文件是静态文件,因此被视为模板。 All static resources are served as-is, without any processing. 所有静态资源都按原样提供,无需任何处理。

All non-absolute URLs in a CSS file are relative to the location from where the CSS file has been loaded; CSS文件中的所有非绝对URL都与加载CSS文件的位置有关; if you use background-image:url("myimage.gif") , the browser loads the image relative to your CSS file location. 如果您使用background-image:url("myimage.gif") ,浏览器将相对于您的CSS文件位置加载图像。 Since the CSS was loaded from http://yoursite/static/mycss.css , the image will be loaded from http://yoursite/static/myimage.gif . 由于CSS是从http://yoursite/static/mycss.css加载的,因此图像将从http://yoursite/static/myimage.gif加载。

Alternatively, if you referencing files from unusual locations (for example, images auto-generated by one of your views), you'll have to add your CSS file as a view instead, and render it with a (text) template. 或者,如果您引用来自异常位置的文件(例如,由您的某个视图自动生成的图像)​​,则必须将CSS文件添加为视图,并使用(文本)模板进行渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM