Bradley Kirton's Blog

Published on May 23, 2023

Go home

Dynamic background images with Django and TailwindCSS

I recently came across an issue when trying to set a background image URL in a Django project using TailwindCSS.

Take this markup for example.

{% load static %}
{% static 'imgs/background.png' as background_image_url %}

<div class="bg-[url('{{ background_image_url }}')]"></div>

The issue here is that when Tailwind parses the template the background_image_url has not been populated in the template.

A simple solution in some circumstances may be to just hard code the image path.

<div class="bg-[url('/static/imgs/background.png')]"></div>

This will not work if you are serving your static files from another domain, for example S3.

I came across a clever solution to this problem on Stack Overflow which makes use of CSS variables.

{% load static %}
{% static 'imgs/background.png' as background_image_url %}

<div
    style="--background-image-url: url('{{ background_image_url }}')"
    class="bg-[image:var(--background-image-url)]">
</div>