Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background image in css style from static files with django

I used this template to create a home page in a django project, however I can't have the background image displayed correctly (bg.jpg)

The background image is used as foollows in the css file :

.wrapper.style3 {
    background-color: #000;
    color: #bfbfbf;
    background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg);
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
    position: relative;
}

I read these topics

  • How to add background image in css?

  • How to use background image in CSS?

  • use static image in css, django

  • How do I put a background image on the body in css with django using static?

and tried all of the solutions but non of them seems to work.

My project tree is like

project_name
- home
- static
--home
---style.css
--images
---bg.jpg
- templates
-- home
---base.html
---home_template.html

in the style.css file I tried the following

background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg);

background-image: url("/media/usr/path_to_project/project_name/home/static/images/bg.jpg");

background-image: url(../images/bg.jpg);

background-image: url("../images/bg.jpg");

background-image: url("{% static 'images.bg.jpg' %});

in my base.html template I have :

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

and in my home_template.html I have

{% block body %}
{% load staticfiles %}

        <section id="two" class="wrapper style3">
            <div class="inner">
                <header class="align-center">
                    <p>Nam vel ante sit amet libero scelerisque facilisis eleifend vitae urna</p>
                    <h2>Morbi maximus justo</h2>
                </header>
            </div>
        </section>

{% endblock %}

The strange thing is that I have other images in my static/images directory that are displayed fine in the template with inline styling such as :

<div class="image fit">
<img src="{% static 'images/pic03.jpg' %}" alt="" />
</div>
like image 617
Boidot Avatar asked Feb 07 '18 13:02

Boidot


2 Answers

You should simply use background-image: url('/static/images/bg.jpg');, since Django automatically maps /static to the correct folder.

like image 174
Jorjon Avatar answered Sep 21 '22 18:09

Jorjon


There is a special setting that handles how static files are served: STATIC_URL.

That is the correct path to use.

like image 40
marcanuy Avatar answered Sep 21 '22 18:09

marcanuy