Use of Django's static templatetag in css file to set a background image

Django static css
Image: Django static css (License: CC-BY-SA Marcelo Canina)

Alternatives to solve static function usage

Published:
Last modified:
Tags Django , Static , Css

Overview

Setting an image as a background property in CSS can be a problem in Django as it recommends to refer to your static files with the static template tag, but then you realize load_static doesn’t work from CSS files.

So how do you do something like background-image: url({% static 'images/cover.jpg' %}); in CSS?

Here are two approaches to solve this issue.

Concept

There is a special setting that handles how static files are served: STATIC_URL.

The static (django.templatetags.dostatic) templatetag, joins the given path with the above mentioned STATIC_URL setting.

In most cases the STATIC_URL settings is /static/, so you can use /static/images/bg.jpg in your CSS as long as this setting doesn’t change.

Having that in mind you can use it, and if not you can choose to apply that style in the HTML directly using {% static 'images/bg.jpg' %}, that way you are sure it will always use the correct setting and be accessible.

Solution 1: Background in HTML

One of the approaches is to set the above property as an inline style in the HTML attributes:

<div style="background-image: url({% static 'images/cover.jpg' %});">
<!-- image -->
</div>

Solution 2: Static path

In CSS, for example myapp/css/static.css:

cover {
	background: url('/static/img/home-cover.jpg');
}

In HTML:

<div class="cover">
<!-- image -->
</div>

References

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


This article explains different approaches to solve the problem of having a background image url set in CSS

Clutter-free software concepts.
Translations English Español

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·