How to refer to static files in my css files?

Use a relative path. Relative to the folder where the css file reside


You can move any CSS that contains static file paths to inline CSS, contained in the template.

i.e.

<div style="background: url('{% static 'logo.png' %}')"></div>

The catch here is that it won't work for @media queries, you'd need to put those in a block, e.g.

<style>
    @media (min-width: 1200px){
       background: url('{% static 'logo.png' %}');
    }
</style>

If you want to use {% static %} tag in your CSS file, you should use {% include %} tag. Here is an example to do so:

foo.html

{% load static %}
{% load i18n %}
{% load widget_tweaks %}

<!DOCTYPE html>
<html>
<head>
    <style>
        {% include "path/to/custom_styles_1.css" %}
    </style>
    <link rel="stylesheet" href="{% static 'css/custom_styles_2.css' %}">
</head>
<body>
<!-- Your HTML body -->
</body>
</html>

custom_styles_1.css

{% load static%}

{
     background: url('{% static "/img/logo.png" %}')
}

custom_styles_2.css

.fa {
    position: relative;
    text-align: center;
    font-family: BTitrBold;
    font-size: 3.5em;
}

.name {
    position: absolute;
    top: 37%;
    right: 15%;
}

.school {
    position: absolute;
    top: 530px;
    right: 200px;
}

.id {
    position: absolute;
    top: 700px;
    right: 200px;
}

.degree {
    position: absolute;
    top: 740px;
    left: 195px;
}

custom_styles_1.css is the CSS file that includes {% static %} tag. You should integrate it with your foo.html file with {% include %} tag. In this way, Django will put all the styles you need at the appropriate place and render the static tags correctly.

custom_styles_2.css is a normal CSS file located in STATIC_ROOT directory, so you can use {% static %} tag for it without any problem.


Use absolute URL from base directory, this will point to any file in a static folder within an app

settings.py:

STATIC_URL = '/static/'

style.css:

background-image: url('/static/img/sample.jpg');