【问题标题】:background image in css style from static files with django来自 django 的静态文件中的 css 样式的背景图像
【发布时间】:2018-07-17 20:26:37
【问题描述】:

我用这个template在一个django项目中创建了一个主页,但是我不能正确显示背景图片(bg.jpg)

背景图片在css文件中被用作傻瓜:

.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;
}

我阅读了这些主题

并尝试了所有解决方案,但似乎没有一个有效。

我的项目树是这样的

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

在 style.css 文件中我尝试了以下

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' %});

在我的 base.html 模板中:

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

在我的 home_template.html 中有

{% 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 %}

奇怪的是,我的 static/images 目录中有其他图像,这些图像在模板中显示良好,具有内联样式,例如:

<div class="image fit">
<img src="{% static 'images/pic03.jpg' %}" alt="" />
</div>

【问题讨论】:

  • 可能您的图片已损坏,或者我之前曾发生过类似的情况,问题是图片的大写字母为.JPG 不小。试试直接从url打开img看看是不是css问题?

标签: css django image django-staticfiles


【解决方案1】:

您应该简单地使用background-image: url('/static/images/bg.jpg');,因为 Django 会自动将/static 映射到正确的文件夹。

【讨论】:

    【解决方案2】:

    有一个特殊的设置可以处理静态文件的服务方式:STATIC_URL

    这是正确的使用路径。

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2014-05-24
      • 2020-10-21
      • 2015-05-07
      • 1970-01-01
      • 2017-06-22
      相关资源
      最近更新 更多