Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

newb to pyramid and python. I've been able to link to my static files successfully in any of my jinja2 templates, ie:

<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.

I'd like to use an image as a background but am having trouble linking to the image in my css file:

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

This link shows up in mycss.css as

"{{'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!

like image 417
user_78361084 Avatar asked Sep 25 '12 16:09

user_78361084


People also ask

How do I link an image in CSS?

Complete HTML/CSS Course 2022 To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image. With that, also add the height and width.

How do you insert an image into a CSS in flask?

First of all you do need static_url_path='/static' while this is the default static folder. Secondly change to background: url("/static/images/cover. jpg") I hope your static folder is under your root folder of project and css folder inside that.


1 Answers

Your CSS file is a static file, and thus is not treated as a template. 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; if you use background-image:url("myimage.gif"), the browser loads the image relative to your CSS file location. Since the CSS was loaded from http://yoursite/static/mycss.css, the image will be loaded from 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.

like image 190
Martijn Pieters Avatar answered Oct 11 '22 16:10

Martijn Pieters