Y7da
Y7da

Reputation: 433

How do I add static url inside CSS file?

I have a CSS class that I need to add a background to it. How do I point my background to the static folder in Django?

E.g:

.background {
	background: url(img/my-background.png) no-repeat;
}

Do I have to add this with a template tag in my base.html instead? Like this:

<style>.background { background: url({% static "img/my-background.png" %}) no-repeat; } </style>

Upvotes: 0

Views: 1436

Answers (1)

Parag Tyagi
Parag Tyagi

Reputation: 8960

Why not simply use Relative Path instead ?

1) settings.py

import os
from path import path

SETTINGS_FILE_FOLDER = path(__file__).parent.abspath()

STATIC_URL = '/static/'

STATIC_PATH = os.path.join(SETTINGS_FILE_FOLDER, '../static')

STATICFILES_DIRS = (
   STATIC_PATH,
)

2) app_name/templates/xyz.html

<link href="{{ STATIC_URL }}app_name/css/style.css" rel="stylesheet" >

3) static/app_name/css/style.css

.class-name {
  background-image: url('../img/logo.png');
}

4) and this should be the folder structure:

project_folder
│   settings.py
│   manage.py    
│
└───app_name
│    │   views.py
│    │   urls.py
│    │   ...
│    │
│    ├───templates
│    │   │   xyz.html
│    │   │   abc.html
│    │   │   ...
│
│
static
│
└───app_name
│    │
│    ├───css
│    │   │   style.css
│    │   │   ...
│    │
│    └───img
│    │   │   logo.png
│    │   │   ...

Upvotes: 2

Related Questions