The way to use background-image in css files with Django

前端 未结 10 1903
离开以前
离开以前 2021-02-05 02:12

I\'d like to use an image file as a background-image on Django. But I do not know how. First, I read this and tried to write like following this in a css file.

相关标签:
10条回答
  • 2021-02-05 03:11

    For some reasons, which I cannot explain the accepted answer did not worked out for me. (I wanted to use a picture as a cover image for the whole body).

    However, here is the alternative that has worked for me for anyone that might be useful for someone that will come across.


    In a css file, which is located in the static file directory, I have wrote the following:

    CSS:

    body {
      background: url(../main/img/picture-name.jpg); 
    }
    

    You do not have to include *'{% load static %}'* in your css file.

    HTML:

    1. include {%load static%} at the top

    2. create a link href to style, as below.

      <link href='{% static "/main/home.css" %}' rel='stylesheet' type='text/css'>

    0 讨论(0)
  • 2021-02-05 03:11

    Although the solutions listed here are right I just want to add one more thing you need to clear your browser's cache(ctrl + f5) after updating your CSS. Refer to this link.

    Django CSS not updating

    0 讨论(0)
  • 2021-02-05 03:13

    Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

    In you settings.py file define STATIC_URL: STATIC_URL = '/static/'

         {% load static %}
         <img src="{% static "my_app/example.jpg" %}" alt="My image"/>
    

    or

         #third{
              background: url('{{ STATIC_URL }}my_app/example.jpg'
         }
    
    0 讨论(0)
  • 2021-02-05 03:13
    background-image: url('{% static '.jpg' %}');
    
    0 讨论(0)
提交回复
热议问题