1

I have following settings for static files

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_my_proj'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root')

In the css file I do this

#mydiv{
    background-image:  url('/img/myimg.png');
}

And my directory structure

project root
 - static_my_proj
  - css
  - img
  - js

I can see from network tab that it looks for the image in static/css/img/myimg.png. However, if I do this then it works. How can I make it without using ../ at the beginning?

#mydiv{
    background-image:  url('../img/myimg.png');
}
3
  • 1
    Have you tried /static/img/myimg.png? Commented Aug 31, 2019 at 5:28
  • There is a slight advantage to using relative paths in your CSS - if you change your static files settings then you will not need to change any of the image paths Commented Aug 31, 2019 at 5:36
  • @IainShelvington /static/img/myimg.png seems to be working. Commented Aug 31, 2019 at 8:08

1 Answer 1

1

You better use {% static 'img/myimg.png %}. Hardcoded paths aren't good, because if you change your static folder, you would have to change all your code. You can't use static in your css files, but in your templates. Your code would look like this:

yourHTML.html:

{% load staticfiles %}

<div id="mydiv" style="background-image: url({% static 'img/myimg.png' %})">

</div>
Sign up to request clarification or add additional context in comments.

2 Comments

I would avoid using inline styles in html.
You can also use a style tag. If then, I would recommend you using django-sekizai to make sure your code is only once in your template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.